﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agresso.Interface.Layer.Gateway;
using System.Data.SqlClient;
using Agresso.Interface.Layer.SQL;
using System.Collections;
using Agresso.Interface.Layer.Domain;
using System.Data;

namespace Agresso.Interface.Layer.Service
{
    public class CommissionInvoiceService
    {
        DataBaseConnectivity m_dataBaseConectivity;
        AcrBatcInputService m_AcrBatcInputService;
        agldimvalueService m_agldimvalueService;
        asuheaderService m_asuheaderService;
        acuheaderService m_acuheaderService;
        AlertService m_alertService;
        VesselService m_vesselService;
        SupplierCustomerService m_suppCusService;
        ProfitCentreService m_profitCentreService;
        ChargeTypeAccountMappingService m_ChargeTypeAccountMappingService;
        ConfigurationSettingService m_configSettingService;
        CommissionManagersLegalEntityService m_commissionManagersLegalEntityService;
        ud_voyageimp_Service m_ud_voyageimp_Service;
        ResponsibleUserService m_ResponsibleUserService;
        bool m_executeByDateProforma = false;
        DateTime m_fromDateProforma = DateTime.Today;
        DateTime m_lastDateProforma = DateTime.Today;
        DateTime m_currentPeriodProforma = DateTime.Today;

        int batchIDCountProforma = Convert.ToInt32(DateTime.Now.ToString("HHmmss"));
        int batchIDRevCountProforma = Convert.ToInt32(DateTime.Now.ToString("HHmmss")) + 500;

        public CommissionInvoiceService()
        {
            m_dataBaseConectivity = new DataBaseConnectivity();
            m_AcrBatcInputService = new AcrBatcInputService();
            m_agldimvalueService = new agldimvalueService();
            m_asuheaderService = new asuheaderService();
            m_alertService = new AlertService();
            m_acuheaderService = new acuheaderService();
            m_vesselService = new VesselService();
            m_suppCusService = new SupplierCustomerService();
            m_profitCentreService = new ProfitCentreService();
            m_ChargeTypeAccountMappingService = new ChargeTypeAccountMappingService();
            m_configSettingService = new ConfigurationSettingService();
            m_commissionManagersLegalEntityService = new CommissionManagersLegalEntityService();
            m_ud_voyageimp_Service = new ud_voyageimp_Service();
            m_ResponsibleUserService = new ResponsibleUserService();
        }

        public void SetTestDateProforma(bool excuteByDate, DateTime fromDate, DateTime lastdate, DateTime currentPerioddate)
        {
            m_executeByDateProforma = excuteByDate;
            m_fromDateProforma = fromDate;
            m_lastDateProforma = lastdate;
            m_currentPeriodProforma = new DateTime(currentPerioddate.Year, currentPerioddate.Month, DateTime.DaysInMonth(currentPerioddate.Year, currentPerioddate.Month));
        }

        public void ExecuteCommissionInvoiceTCReletType()
        {
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();

                IList invoiceNumbers = new ArrayList();
                SqlCommand cmd = new SqlCommand(CommisionInvoiceSQL.GetCommisionInvoiceInvoiceNumberByTCReletTypeAndInvoiceTypeCommissionFromInterfacePending()
                   , m_dataBaseConectivity.InterfaceSqlConnection);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    invoiceNumbers.Add(rd["invoice_number"].ToString());
                }
                rd.Close();

                IList commissionInvoices = new ArrayList();
                foreach (string invoice_number in invoiceNumbers)
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByTCReletTypeAndInvoiceTypeCommissionFromInterfacePendingByInvoiceNumber();
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("invoice_number", SqlDbType.NVarChar).Value = invoice_number;
                    rd = cmd.ExecuteReader();
                    CommissionInvoice header = null;
                    while (rd.Read())
                    {
                        if (header == null)
                            header = new CommissionInvoice(rd, true);
                        CommissionInvoice item = new CommissionInvoice(rd, true);
                        item.Header = header;
                        header.Items.Add(item);
                    }
                    rd.Close();
                    commissionInvoices.Add(header);
                }
                //string prevclient = "";
                //string prevbatchID = "";

                string prevProfitCentreClient = "";
                int batchIDCount = Convert.ToInt16(DateTime.Now.ToString("ss"));

                foreach (CommissionInvoice ci in commissionInvoices)
                {

                    // if (ci.invoice_number != "EVERSP/1605") continue;

                    SupplierCustomer supplier = m_suppCusService.GetSupplierMapping(ci.company);
                    m_vesselService.FindVesselByName(ci.vessel_name, ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    // ChargeTypeAccountMapping chargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(ci.charge_type);
                    if (supplier.interco)
                    #region InterCo REgion
                    {
                        //continue;
                        ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                        string alert = "";
                        supplier.ProfitCentre = m_profitCentreService.GetProfitCentreByID(supplier.ProfitCentre.profit_centre_id); //ProfitCentre interco
                        Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                        bool validVoyage = m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);
                        // ResponsibleUser user = m_ResponsibleUserService.GetResponsibleUserByName(ci.raised_to_final_by);
                        if (supplier.apar_gr_id.Trim().ToUpper() == "SBR")
                        {
                            agldimvalue icVessel = m_agldimvalueService.GetICVesselDimValue(profitCentreVessel == null ? "XXX" : profitCentreVessel.agr_dim_value);
                            if (profitCentreVessel != null && icVessel == null) { alert += string.Format("-[E012] Unable to find IC Vessel value Code for Vessel '{0}' \r\n", profitCentreVessel.agr_dim_value); } //alert could not  find vessel dim val
                        }
                        if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); } //alert couldnot find map profit centre on vessel-----
                        if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}'\r\n", profitCentreVessel.vessel_name); } //alert could not  find vessel dim val
                        if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E009] Unable to find Dim_Val Code for Profit Centre '{0}'\r\n", profitCentre.full_name); }//alert couldnot map dim_val on profit centre------
                        if (supplier.ProfitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}'\r\n", supplier.ProfitCentre.full_name); }//alert couldnot map client on profit centre------
                        if (supplier.interco_apar_id == "") { alert += string.Format("-[E005] Unable to find apar_id for Supplier '{0}' ", supplier.full_name); }//alert coulnot map company apar_id--------
                        if (supplier.ProfitCentre.agr_dim_value == "") { alert += string.Format("-[E009] Unable to find Dim_Val Code for Profit Centre '{0}'\r\n", supplier.ProfitCentre.full_name); }//alert could not verify company profitcentre dim val -------
                        if (supplier.ProfitCentre.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find CostCentre Code for Profit Centre '{0}' \r\n", supplier.ProfitCentre.full_name); }//alert could not verify company profitcentre dim val -------
                        if (supplier.ProfitCentre.expense_account == "") { alert += string.Format("-[E004] Please set GL account for Profit Centre '{0}' \r\n", supplier.ProfitCentre.full_name); }//alert couldnot map dim_val on profit centre------
                        if (supplier.ProfitCentre.ccc_dim_value == "") { alert += string.Format("-[E003] Please set CostCentre account for Profit Centre '{0}' \r\n", supplier.ProfitCentre.full_name); }//alert couldnot map dim_val on profit centre------
                        if (!validVoyage)
                        {
                            alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n", ci.vessel_name.Trim(), ci.voyage_no
                                , (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                        }

                        if (alert != "")
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                            }
                            continue;
                        }

                        //AP LINE-----------------------------
                        IList acrbatchinputList = new ArrayList();
                        int voucherNumber = GetVoucherRunningNumber();
                        if (prevProfitCentreClient != profitCentre.client)
                            batchIDCount++;
                        string batchID = "SB" + DateTime.Now.ToString("ddMMyyyyHHmm") + batchIDCount.ToString().PadLeft(2, '0');
                        prevProfitCentreClient = supplier.ProfitCentre.client;

                        acrbatchinput acrbatchinput_AP_1 = new acrbatchinput();
                        acrbatchinput_AP_1.voucher_type = "SB";
                        acrbatchinput_AP_1.trans_type = "AP";
                        acrbatchinput_AP_1.client = supplier.ProfitCentre.client;
                        acrbatchinput_AP_1.apar_type = "P";
                        acrbatchinput_AP_1.apar_id = supplier.interco_apar_id;
                        acrbatchinput_AP_1.apar_name = supplier.agr_supp_apar_name;
                        acrbatchinput_AP_1.account = "";
                        acrbatchinput_AP_1.dim_1 = supplier.ProfitCentre.agr_rel_value;//carina 18042013 intercoVessel.agr_rel_value;
                        acrbatchinput_AP_1.dim_2 = "";
                        acrbatchinput_AP_1.dim_3 = "";
                        acrbatchinput_AP_1.dim_4 = "";// profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        acrbatchinput_AP_1.dim_5 = profitCentreVessel.agr_dim_value;//carina18042013 intercoVessel.agr_dim_value;
                        acrbatchinput_AP_1.dim_6 = supplier.ProfitCentre.agr_dim_value;
                        acrbatchinput_AP_1.dim_7 = "";
                        acrbatchinput_AP_1.tax_code = "";// 09 Apr 2013 Carina"0";
                        acrbatchinput_AP_1.tax_system = "";
                        acrbatchinput_AP_1.currency = ci.invoice_currency;
                        acrbatchinput_AP_1.cur_amount = -ci.invoice_amount;
                        acrbatchinput_AP_1.amount = -ci.invoice_amount;
                        acrbatchinput_AP_1.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                        acrbatchinput_AP_1.trans_date = ci.invoice_date;
                        acrbatchinput_AP_1.voucher_date = ci.invoice_date;
                        acrbatchinput_AP_1.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina
                        acrbatchinput_AP_1.ext_inv_ref = ci.invoice_number;
                        acrbatchinput_AP_1.status = "N";
                        acrbatchinput_AP_1.due_date = ci.invoice_due_date;
                        acrbatchinput_AP_1.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                        acrbatchinput_AP_1.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                        acrbatchinput_AP_1.batch_id = batchID;
                        acrbatchinput_AP_1.interface_ = "SB";//18072013 "BI";//"SB";
                        acrbatchinput_AP_1.disc_date = DateTime.Now; //09062013
                        acrbatchinput_AP_1.pay_temp_id = "IM";//09062013
                        acrbatchinput_AP_1.sequence_no = GetSequenceRunningNumber();
                        acrbatchinputList.Add(acrbatchinput_AP_1);

                        //GL LINE----------
                        decimal totalGL_1 = 0;
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            acrbatchinput acrbatchinput_GL_1 = new acrbatchinput();
                            acrbatchinput_GL_1.voucher_type = "SB";
                            acrbatchinput_GL_1.trans_type = "GL";
                            acrbatchinput_GL_1.client = supplier.ProfitCentre.client;
                            acrbatchinput_GL_1.apar_type = "";
                            acrbatchinput_GL_1.apar_id = supplier.interco_apar_id;
                            acrbatchinput_GL_1.apar_name = supplier.agr_supp_apar_name;
                            acrbatchinput_GL_1.account = "2904";
                            acrbatchinput_GL_1.dim_1 = supplier.ProfitCentre.agr_rel_value; //profitCentreVessel.agr_rel_value;//23042013Carina intercoVessel.agr_rel_value;// CArina 17Apr2013
                            acrbatchinput_GL_1.dim_2 = supplier.ProfitCentre.expense_account;// profitCentre.expense_account;// 610/602->"5103" 501->"5102";
                            acrbatchinput_GL_1.dim_3 = "";
                            acrbatchinput_GL_1.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_1.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_1.dim_6 = supplier.ProfitCentre.agr_dim_value;
                            acrbatchinput_GL_1.dim_7 = profitCentre.agr_dim_value;

                            if (acrbatchinput_GL_1.dim_7 == acrbatchinput_GL_1.dim_6) // Carina 09Apr2013
                            {
                                acrbatchinput_GL_1.dim_2 = "";
                                acrbatchinput_GL_1.account = supplier.ProfitCentre.expense_account;//profitCentre.expense_account;
                                acrbatchinput_GL_1.dim_7 = "";
                                acrbatchinput_GL_1.dim_1 = profitCentreVessel.agr_rel_value;
                            }

                            acrbatchinput_GL_1.tax_code = "";// 09 Apr 2013 Carina"0";//carina 08-04-2013
                            acrbatchinput_GL_1.tax_system = "ZI";//carina 08-04-2013
                            acrbatchinput_GL_1.currency = ci.invoice_currency;
                            decimal commissionAmount = item.GetCommissionCreditTCorVCReletAmountRevision1();//04092013 item.GetCommissionCreditTCorVCReletAmount();
                            //if (acrbatchinput_AP_1.amount < 0)
                            //    commissionAmount = commissionAmount < 0 ? -commissionAmount : commissionAmount;
                            //else if (acrbatchinput_AP_1.amount > 0)
                            //{
                            //    commissionAmount = commissionAmount < 0 ? -commissionAmount : commissionAmount;
                            //    commissionAmount = -commissionAmount;
                            //}
                            acrbatchinput_GL_1.cur_amount = commissionAmount;// item.collect_comm == 0 ? item.charge_collect_comm : ci.collectCommissionOneTCRelet() ? item.collect_comm : item.collect_comm2;// ci.invoice_amount;
                            acrbatchinput_GL_1.amount = acrbatchinput_GL_1.cur_amount;// item.GetCommissionAmountTCRelet();//item.collect_comm == 0 ? item.charge_collect_comm : ci.collectCommissionOneTCRelet() ? item.collect_comm : item.collect_comm2;// ci.invoice_amount;
                            acrbatchinput_GL_1.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL_1.trans_date = ci.invoice_date;
                            acrbatchinput_GL_1.voucher_date = ci.invoice_date;
                            acrbatchinput_GL_1.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;
                            acrbatchinput_GL_1.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_1.status = "N";
                            acrbatchinput_GL_1.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_1.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_1.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_1.batch_id = batchID;
                            acrbatchinput_GL_1.interface_ = "SB";//18072013 "BI";//"SB";
                            acrbatchinput_GL_1.sequence_no = GetSequenceRunningNumber();
                            acrbatchinput_GL_1.disc_date = DateTime.Now; //09062013
                            acrbatchinput_GL_1.pay_temp_id = "IM";//09062013
                            acrbatchinputList.Add(acrbatchinput_GL_1);
                            totalGL_1 += acrbatchinput_GL_1.amount;
                        }

                        acrbatchinput acrbatchinput_AP_2 = new acrbatchinput();
                        acrbatchinput_AP_2.voucher_type = "SB";
                        acrbatchinput_AP_2.trans_type = "AP";
                        acrbatchinput_AP_2.client = supplier.ProfitCentre.client;
                        acrbatchinput_AP_2.apar_type = "P";
                        acrbatchinput_AP_2.apar_id = supplier.interco_apar_id;
                        acrbatchinput_AP_2.apar_name = supplier.agr_supp_apar_name;
                        acrbatchinput_AP_2.account = "";
                        acrbatchinput_AP_2.dim_1 = supplier.ProfitCentre.agr_rel_value;//carina 18042013intercoVessel.agr_rel_value;
                        acrbatchinput_AP_2.dim_2 = "";
                        acrbatchinput_AP_2.dim_3 = "";
                        acrbatchinput_AP_2.dim_4 = "";// profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        acrbatchinput_AP_2.dim_5 = profitCentreVessel.agr_dim_value;//carina18042013 intercoVessel.agr_dim_value;
                        acrbatchinput_AP_2.dim_6 = supplier.ProfitCentre.agr_dim_value;
                        acrbatchinput_AP_2.dim_7 = "";// profitCentre.agr_dim_value; //"";Carina17Apr2013
                        acrbatchinput_AP_2.tax_code = "";// 09 Apr 2013 Carina"0";
                        acrbatchinput_AP_2.tax_system = "";
                        acrbatchinput_AP_2.currency = ci.invoice_currency;
                        acrbatchinput_AP_2.cur_amount = ci.invoice_amount;
                        acrbatchinput_AP_2.amount = ci.invoice_amount;
                        acrbatchinput_AP_2.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                        acrbatchinput_AP_2.trans_date = ci.invoice_date;
                        acrbatchinput_AP_2.voucher_date = ci.invoice_date;
                        acrbatchinput_AP_2.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;
                        acrbatchinput_AP_2.ext_inv_ref = ci.invoice_number;
                        acrbatchinput_AP_2.status = "N";
                        acrbatchinput_AP_2.due_date = ci.invoice_due_date;
                        acrbatchinput_AP_2.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                        acrbatchinput_AP_2.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                        acrbatchinput_AP_2.batch_id = batchID;
                        acrbatchinput_AP_2.interface_ = "SB";//18072013 "BI";//"SB";
                        acrbatchinput_AP_2.sequence_no = GetSequenceRunningNumber();
                        acrbatchinput_AP_2.disc_date = DateTime.Now; //09062013
                        acrbatchinput_AP_2.pay_temp_id = "IM";//09062013
                        acrbatchinputList.Add(acrbatchinput_AP_2);

                        decimal totalGL_2 = 0;
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            acrbatchinput acrbatchinput_GL_2 = new acrbatchinput();
                            acrbatchinput_GL_2.voucher_type = "SB";
                            acrbatchinput_GL_2.trans_type = "GL";
                            acrbatchinput_GL_2.client = supplier.ProfitCentre.client;
                            acrbatchinput_GL_2.apar_type = "";
                            acrbatchinput_GL_2.apar_id = supplier.interco_apar_id;
                            acrbatchinput_GL_2.apar_name = supplier.agr_supp_apar_name;
                            acrbatchinput_GL_2.account = "5301";//Carina17042013 "5301";
                            acrbatchinput_GL_2.dim_1 = supplier.ProfitCentre.agr_rel_value;//20072013 profitCentreVessel.agr_rel_value;//08052013company.ProfitCentre.ccc_dim_value;
                            //profitCentreVessel.agr_rel_value;//23042013Carina// intercoVessel.agr_rel_value; 17 Apr 2013 Carina
                            acrbatchinput_GL_2.dim_2 = "";
                            acrbatchinput_GL_2.dim_3 = "";
                            acrbatchinput_GL_2.dim_4 = "";// profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_2.dim_5 = profitCentreVessel.agr_dim_value; //intercoVessel.agr_dim_value; 17Apr2013-CArina
                            acrbatchinput_GL_2.dim_6 = supplier.ProfitCentre.agr_dim_value;
                            acrbatchinput_GL_2.dim_7 = "";
                            acrbatchinput_GL_2.tax_code = "ZO";//carina 08-04-2013
                            acrbatchinput_GL_2.tax_system = "";
                            acrbatchinput_GL_2.currency = ci.invoice_currency;
                            decimal commissionAmount = item.GetCommissionCreditTCorVCReletAmountRevision1();//04092013  item.GetCommissionCreditTCorVCReletAmount();
                            //if (acrbatchinput_AP_2.amount < 0)
                            //    commissionAmount = commissionAmount < 0 ? -commissionAmount : commissionAmount;
                            //else if (acrbatchinput_AP_2.amount > 0)
                            //{
                            //    commissionAmount = commissionAmount < 0 ? -commissionAmount : commissionAmount;
                            //    commissionAmount = -commissionAmount;
                            //}
                            acrbatchinput_GL_2.cur_amount = -commissionAmount;// item.collect_comm == 0 ? item.charge_collect_comm : ci.collectCommissionOneTCRelet() ? item.collect_comm : item.collect_comm2;// ci.invoice_amount;
                            acrbatchinput_GL_2.amount = acrbatchinput_GL_2.cur_amount;// -(item.collect_comm == 0 ? item.charge_collect_comm : ci.collectCommissionOneTCRelet() ? item.collect_comm : item.collect_comm2);//ci.invoice_amount;
                            acrbatchinput_GL_2.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL_2.trans_date = ci.invoice_date;
                            acrbatchinput_GL_2.voucher_date = ci.invoice_date;
                            acrbatchinput_GL_2.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;
                            acrbatchinput_GL_2.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_2.status = "N";
                            acrbatchinput_GL_2.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_2.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_2.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_2.batch_id = batchID;
                            acrbatchinput_GL_2.interface_ = "SB";//18072013 "BI";//"SB";
                            acrbatchinput_GL_2.sequence_no = GetSequenceRunningNumber();
                            acrbatchinput_GL_2.disc_date = DateTime.Now; //09062013
                            acrbatchinput_GL_2.pay_temp_id = "IM";//09062013
                            acrbatchinputList.Add(acrbatchinput_GL_2);
                            totalGL_2 += acrbatchinput_GL_2.amount;
                        }
                        if ((acrbatchinput_AP_1.amount + totalGL_1 != 0) || (acrbatchinput_AP_2.amount + totalGL_2 != 0))
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                        //IC VOYAGE VALIDATION-----------28052013
                        acrbatchinput acr2904 = (acrbatchinput)acrbatchinputList[1];
                        if (acr2904.account.Trim() == "2904" && acr2904.dim_7 != "")
                        {
                            agldimvalue icVoyage = m_agldimvalueService.GetICVoyageDimValue((profitCentreVessel == null ? "XXX" : (profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'))));
                            if (profitCentreVessel != null && icVoyage == null) { alert += string.Format("-[E013] Unable to find IC Voyage value Code for Voyage '{0}' \r\n", profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0')); } //alert could not  find vessel dim val
                            if (alert != "")
                            {
                                foreach (CommissionInvoice item in ci.Items)
                                    updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                                continue;
                            }
                        }
                        //IC VOYAGE VALIDATION-----------28052013
                        string agrtid = "";
                        foreach (acrbatchinput acr in acrbatchinputList)
                        {
                            m_AcrBatcInputService.Insert(acr);
                            m_AcrBatcInputService.InsertToInterfaceTable(acr);
                            agrtid += ";" + acr.agrtid.ToString();
                        }
                        //update status-------
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                            cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                            cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                            cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                            cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                            cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                            cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                            cmd.ExecuteNonQuery();
                        }
                    }
                    #endregion
                    else
                    #region NonInterco Broker
                    {
                        ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                        //ResponsibleUser user = m_ResponsibleUserService.GetResponsibleUserByName(ci.raised_to_final_by);
                        string alert = "";

                        //if (company.agr_supp_apar_id == "") { alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", company.full_name); };
                        if (profitCentre.CommissionManager.profit_centre_id == 0) { alert += string.Format("-[E014] Unable to find Legal entity for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                        if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E011] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                        //01072013 
                        ProfitCentre legalEntity = m_profitCentreService.GetProfitCentreByID(profitCentre.CommissionManager.profit_centre_id);
                        //01072013 Vessel legalEntityVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentreCommissionManager.profit_centre_id, ci.vessel_name.Trim(), profitCentreCommissionManager.client);
                        //if (legalEntityVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' for Profit Centre '{1} {2}' \r\n", ci.vessel_name.Trim(), profitCentreCommissionManager.full_name, profitCentreCommissionManager.agr_dim_value); }
                        //if (legalEntityVessel != null && legalEntityVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}-{1}' \r\n", legalEntityVessel.vessel_name, legalEntityVessel.agr_dim_value); }//alert
                        //if (legalEntityVessel != null && legalEntityVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", legalEntityVessel.vessel_name); }//alert
                        Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client);
                        bool validVoyage = m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);
                        if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                        if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                        if (!validVoyage)
                        {
                            alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage:  '{1}' Code:'{2}' \r\n",
                                ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "_V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                        }
                        if (supplier.apar_gr_id.Trim().ToUpper() == "SBR")
                        {
                            agldimvalue icVessel = m_agldimvalueService.GetICVesselDimValue(profitCentreVessel == null ? "XXX" : profitCentreVessel.agr_dim_value);
                            if (profitCentreVessel != null && icVessel == null) { alert += string.Format("-[E012] Unable to find IC Vessel value Code for Vessel '{0}' \r\n", profitCentreVessel.agr_dim_value); } //alert could not  find vessel dim val
                        }

                        if (alert != "")
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                            }
                            //m_alertService.CheckAndUpdateAlert(ci.commission_invoice_id.ToString(), AlertType.SOFTMAR_COMMISSION_INVOICE_TCRELET, AlertStatus.PENDING,
                            //    string.Format("Failed while interfacing Invoice No.{0}, Invoice Date :{3}, Company Name : {1}, Description : {2}  \r\n", ci.invoice_number, ci.company, ci.charge_description, ci.invoice_date.ToString("dd-MMM-yyyy")) + alert, ci.invoice_number);
                            continue;
                        }
                        //else
                        //{
                        //    m_alertService.CheckAndUpdateAlert(ci.commission_invoice_id.ToString(), AlertType.SOFTMAR_COMMISSION_INVOICE_TCRELET, AlertStatus.RESOLVED,
                        //          string.Format("Failed while interfacing Invoice No.{0}, Invoice Date :{3}, Company Name : {1}, Description : {2}  \r\n", ci.invoice_number, ci.company, ci.charge_description, ci.invoice_date.ToString("dd-MMM-yyyy")) + alert, ci.invoice_number);
                        //}
                        IList acrbatchinputList = new ArrayList();
                        int voucherNumber = GetVoucherRunningNumber();
                        //string batchID = "SB" + DateTime.Now.ToString("ddMMyyyyHHmmss"); 01072013
                        if (prevProfitCentreClient != profitCentre.client)
                            batchIDCount++;
                        string batchID = "SE" + DateTime.Now.ToString("ddMMyyyyHHmm") + batchIDCount.ToString().PadLeft(2, '0');
                        prevProfitCentreClient = profitCentre.client;

                        DateTime periodDate = DateTime.Today;// new DateTime(2013, 9, 30);
                        int period = Convert.ToInt32(periodDate.ToString("yyyyMM"));

                        acrbatchinput acrbatchinput_AP = new acrbatchinput();
                        // acrbatchinput_AP.voucher_type = "SB"; 01072013
                        acrbatchinput_AP.voucher_type = "SE";
                        //acrbatchinput_AP.trans_type = "AP";01072013
                        acrbatchinput_AP.trans_type = "GL";
                        acrbatchinput_AP.client = profitCentre.client;//28082013 legalEntity.client;//04072013 profitCentre.client;//01072013 profitCentreCommissionManager.client;
                        acrbatchinput_AP.apar_type = "";//04072013 "P";
                        //acrbatchinput_AP.apar_id = company.agr_supp_apar_id; 01072013
                        acrbatchinput_AP.apar_name = "";//04072013 company.agr_supp_apar_name;
                        acrbatchinput_AP.account = "3302";//28082013 "2904";//04072013 "3051";//Carina17042013"";
                        acrbatchinput_AP.dim_1 = legalEntity.agr_rel_value;//04072013 profitCentre.agr_rel_value;//01072013 profitCentreCommissionManager.agr_rel_value;//carina18042013 legalEntityVessel.agr_rel_value;
                        acrbatchinput_AP.dim_2 = "";//28032013 "3302";//04072013
                        acrbatchinput_AP.dim_3 = "";
                        acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //04072013 // legalEntityVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');// Carina - 04Apr2013
                        acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value; //carina18042013 legalEntityVessel.agr_dim_value;
                        acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;//28082013 legalEntity.agr_dim_value;//04072013 profitCentre.agr_dim_value;//01072013 profitCentreCommissionManager.agr_dim_value;
                        acrbatchinput_AP.dim_7 = "";//28082013 profitCentre.agr_dim_value;//04072013 "";
                        acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina"0";
                        acrbatchinput_AP.tax_system = "";
                        acrbatchinput_AP.currency = ci.invoice_currency;
                        acrbatchinput_AP.cur_amount = -ci.invoice_amount;
                        acrbatchinput_AP.amount = -ci.invoice_amount;
                        acrbatchinput_AP.description = ci.invoice_number; //03072013 ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                        acrbatchinput_AP.trans_date = ci.invoice_date;
                        acrbatchinput_AP.voucher_date = ci.invoice_date;
                        acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;
                        acrbatchinput_AP.ext_inv_ref = "";//03072013 ci.invoice_number;
                        acrbatchinput_AP.status = "N";
                        acrbatchinput_AP.due_date = ci.invoice_due_date;
                        acrbatchinput_AP.period = period;
                        acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                        acrbatchinput_AP.batch_id = batchID;
                        acrbatchinput_AP.interface_ = "BI";//20072013"BI";//"SB";
                        acrbatchinput_AP.disc_date = DateTime.Now; //09062013
                        acrbatchinput_AP.pay_temp_id = "";//04072013 "IM";//09062013
                        acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                        //if dim_6 == dim_7 08072013
                        //28082013 if (acrbatchinput_AP.dim_7 == acrbatchinput_AP.dim_6)
                        //28082013 {
                        //28082013     acrbatchinput_AP.dim_7 = "";//08072013
                        //28082013     acrbatchinput_AP.account = acrbatchinput_AP.dim_2;//08072013
                        //28082013     acrbatchinput_AP.dim_2 = "";//08072013
                        //28082013 }
                        acrbatchinputList.Add(acrbatchinput_AP);

                        decimal totalGL = 0;
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SE";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;//28082013 legalEntity.client;//04072013 profitCentre.client;//01072013 profitCentreCommissionManager.client;
                            acrbatchinput_GL.apar_type = "";
                            acrbatchinput_GL.apar_id = "";//04072013 company.agr_supp_apar_id;
                            acrbatchinput_GL.apar_name = "";//04072013 company.agr_supp_apar_name;
                            acrbatchinput_GL.account = "5101";//28082013 "2904"; //;//carina 08-04-2013 02Apr2013
                            acrbatchinput_GL.dim_1 = legalEntity.agr_rel_value;//04072013 profitCentre.agr_rel_value;//01072013 profitCentreCommissionManager.agr_rel_value;//23042013Carina carina18042013 "";
                            acrbatchinput_GL.dim_2 = "";//28082013 "5101";//04072013 profitCentre.expense_account; //carina-14052013//"5101";//"5103"; //;//carina 08-04-2013  02Apr2013
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.agr_dim_value;//28082013 legalEntity.agr_dim_value; //04072013 profitCentre.agr_dim_value;//01072013 profitCentreCommissionManager.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";//28082013 profitCentre.agr_dim_value;//07-8-04-2013 Carina- 02Apr2013
                            acrbatchinput_GL.tax_code = "0";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL.tax_system = "";// 09 Apr 2013 Carina "0";//if outside singapore should have tax.. 08-04-2013 Carina.

                            //04072013 if (acrbatchinput_GL.dim_7 == acrbatchinput_GL.dim_6) // Carina 09Apr2013
                            //{
                            //    acrbatchinput_GL.account = "5101";//carina14052013--profitCentre.expense_account; //5101 //Carina17042013-3rd broker profitCentre.expense_account;
                            //    acrbatchinput_GL.dim_2 = "";
                            //    acrbatchinput_GL.dim_7 = "";
                            //    acrbatchinput_GL.dim_1 = profitCentreVessel.agr_rel_value;
                            //    acrbatchinput_GL.tax_code = "ZI";
                            //}
                            //  if (acrbatchinput_GL_2.dim_7 != "") //Carina17042013 interlegal entity dim_7
                            //  {
                            //      acrbatchinput_GL_2.account = legalEntity.expense_account;// profitCentre.expense_account;
                            //      
                            // }
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = item.GetCommissionCreditTCorVCReletAmountRevision1();//04092013 item.GetCommissionCreditTCorVCReletAmount();// item.collect_comm == 0 ? item.charge_collect_comm : ci.collectCommissionOneTCRelet() ? item.collect_comm : item.collect_comm2;// ci.invoice_amount;
                            acrbatchinput_GL.amount = item.GetCommissionCreditTCorVCReletAmountRevision1();//04092013 item.GetCommissionCreditTCorVCReletAmount();//item.collect_comm == 0 ? item.charge_collect_comm : ci.collectCommissionOneTCRelet() ? item.collect_comm : item.collect_comm2;//ci.invoice_amount;
                            acrbatchinput_GL.description = item.charge_type + " : " + item.narrative + "-" + item.invoice_number + "-" + item.raised_to_final_by + " " + item.invoice_number ; //(item.charge_collect_comm > 0 ? "Charge Collect Commission" : item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by) + " " + item.invoice_number;
                            acrbatchinput_AP.description = (item.charge_collect_comm > 0 ? "Charge Collect Commission " + item.company : item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by) + " " + item.invoice_number + " " + item.company; //09122013 acrbatchinput_GL.description;//04072013 follow the detail description
                            acrbatchinput_GL.trans_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1; 1;
                            acrbatchinput_GL.ext_inv_ref = "";//04072013 ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = period;
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "BI";//20072013"BI";//"SB";
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinput_GL.disc_date = DateTime.Now; //09062013
                            acrbatchinput_GL.pay_temp_id = "";//04072013  "IM";//09062013
                            //if dim_6 == dim_7 08072013
                            //28082013 if (acrbatchinput_GL.dim_7 == acrbatchinput_GL.dim_6)
                            //28082013 {
                            //28082013     acrbatchinput_GL.dim_7 = "";//08072013
                            //28082013     acrbatchinput_GL.account = acrbatchinput_GL.dim_2;//08072013
                            //28082013     acrbatchinput_GL.dim_2 = "";//08072013
                            //28082013 }
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;
                        }
                        if (acrbatchinput_AP.amount + totalGL != 0)
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                        //IC VOYAGE VALIDATION-----------28052013
                        acrbatchinput acr2904 = (acrbatchinput)acrbatchinputList[1];
                        if (acr2904.account.Trim() == "2904" && acr2904.dim_7 != "")
                        {
                            agldimvalue icVoyage = m_agldimvalueService.GetICVoyageDimValue((profitCentreVessel == null ? "XXX" : (profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'))));
                            if (profitCentreVessel != null && icVoyage == null) { alert += string.Format("-[E013] Unable to find IC Voyage value Code for Voyage '{0}' \r\n", profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0')); } //alert could not  find vessel dim val
                            if (alert != "")
                            {
                                foreach (CommissionInvoice item in ci.Items)
                                    updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                                continue;
                            }
                        }
                        //IC VOYAGE VALIDATION-----------28052013

                        string agrtid = "";
                        foreach (acrbatchinput acr in acrbatchinputList)
                        {
                            acr.description = acr.description.Length > 255 ? acr.description.Substring(0, 255) : acr.description;
                            m_AcrBatcInputService.Insert(acr);
                            m_AcrBatcInputService.InsertToInterfaceTable(acr);
                            agrtid += ";" + acr.agrtid.ToString();
                        }
                        //update status-------
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                            cmd.Parameters.Clear();
                            cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                            cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                            cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                            cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                            cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                            cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                            cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                            cmd.ExecuteNonQuery();
                        }

                        // ---------------------
                    }

                    #endregion
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        private void updateRemarks(int p, string alert, string oldAlert, string pickupFlag)
        {
            if (alert == oldAlert) return;
            m_dataBaseConectivity.InterfaceSqlConnection_b.Open();
            SqlCommand cmd = new SqlCommand(CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus(), m_dataBaseConectivity.InterfaceSqlConnection_b);
            cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = pickupFlag;
            cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
            cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
            cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = "";
            cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = p;
            cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = alert;
            cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = "";
            cmd.ExecuteNonQuery();
            m_dataBaseConectivity.InterfaceSqlConnection_b.Close();
        }

        public void ExecuteCommissionInvoiceTCReletTypeChargeDebit()
        {
           // int teset = 0;
            try
            {
                IList invoiceNumbers = new ArrayList();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand(CommisionInvoiceSQL.GetCommisionInvoiceInvoiceNumberByTCReletTypeAndInvoiceTypeChargeDebitFromInterfacePending()
                  , m_dataBaseConectivity.InterfaceSqlConnection);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                    invoiceNumbers.Add(rd["invoice_number"].ToString());
                rd.Close();

                IList invoiceTC = new ArrayList();
                foreach (string invoice_number in invoiceNumbers)
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByTCReletTypeAndInvoiceTypeChargeDebitFromInterfacePendingByInvoiceNumber();
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("invoice_number", SqlDbType.NVarChar).Value = invoice_number;
                    rd = cmd.ExecuteReader();
                    CommissionInvoice header = null;
                    while (rd.Read())
                    {
                        if (header == null)
                            header = new CommissionInvoice(rd, true);
                        CommissionInvoice item = new CommissionInvoice(rd, true);
                        item.Header = header;
                        header.Items.Add(item);
                    }
                    rd.Close();
                    invoiceTC.Add(header);
                }
                string prevProfitCentreClient = "";
                int batchIDCount = Convert.ToInt16(DateTime.Now.ToString("ss"));

                foreach (CommissionInvoice ci in invoiceTC)
                {
                   // teset++;
                  //  if (teset == 66)
                  //  {
 
                  //  }
                    SupplierCustomer customer = m_suppCusService.GetCustomerMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    //ResponsibleUser user = m_ResponsibleUserService.GetResponsibleUserByName(ci.raised_to_final_by);
                    m_vesselService.FindVesselByName(ci.vessel_name,ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    string alert = "";
                    if (customer.agr_cust_apar_id == "")
                    {
                        alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", customer.full_name);
                    };
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);
                    //agldimvalue icVessel = m_agldimvalueService.GetICVesselDimValue(profitCentreVessel == null ? "XXX" : profitCentreVessel.agr_dim_value);
                    //agldimvalue icVoyage = m_agldimvalueService.GetICVoyageDimValue((profitCentreVessel == null ? "XXX" : (profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'))));

                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    //  if (profitCentreVessel != null && icVessel == null) { alert += string.Format("-Unable to find IC Vessel value Code for Vessel '{0}' \r\n", profitCentreVessel.agr_dim_value); } //alert could not  find vessel dim val
                    //  if (profitCentreVessel != null && icVoyage == null) { alert += string.Format("-Unable to find IC Voyage value Code for Voyage '{0}' \r\n", profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0')); } //alert could not  find vessel dim val
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }
                    //if (chargeType.freighthire_account == "") { alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'", chargeType.charge_type); } //alert coudnot map account on charge type :---------

                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.chartererInv_account == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'  \r\n", itemChargeType.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        continue;
                    }

                    if (prevProfitCentreClient != profitCentre.client)
                        batchIDCount++;
                    string batchID = "SD" + DateTime.Now.ToString("ddMMyyyyHHmm") + batchIDCount.ToString().PadLeft(2, '0');
                    prevProfitCentreClient = profitCentre.client;

                    IList acrbatchinputList = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();
                    acrbatchinput acrbatchinput_AP = new acrbatchinput();
                    acrbatchinput_AP.voucher_type = "SD";
                    acrbatchinput_AP.trans_type = "AR";
                    acrbatchinput_AP.client = profitCentre.client;
                    acrbatchinput_AP.apar_type = "R";
                    acrbatchinput_AP.apar_id = customer.agr_cust_apar_id;
                    acrbatchinput_AP.apar_name = customer.agr_cust_apar_name;
                    acrbatchinput_AP.account = "";
                    acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                    acrbatchinput_AP.dim_2 = "";
                    acrbatchinput_AP.dim_3 = "";
                    //13092013 ---- TC RELET
                    acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                    acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                    acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;
                    acrbatchinput_AP.dim_7 = "";
                    acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                    acrbatchinput_AP.tax_system = "";
                    acrbatchinput_AP.currency = ci.invoice_currency;
                    acrbatchinput_AP.cur_amount = ci.invoice_amount;
                    acrbatchinput_AP.amount = ci.invoice_amount;
                    acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                    acrbatchinput_AP.trans_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                    acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                    acrbatchinput_AP.status = "N";
                    acrbatchinput_AP.due_date = ci.invoice_due_date;
                    acrbatchinput_AP.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                    acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                    acrbatchinput_AP.batch_id = batchID;
                    acrbatchinput_AP.interface_ = "SD";
                    acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                    acrbatchinput_AP.pay_temp_id = "IM";//09062013
                    acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                    acrbatchinputList.Add(acrbatchinput_AP);

                    decimal totalGL = 0;
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        if (item.narrative_line == 70)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Address Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SD";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cad.chartererInv_account;// "5252 ";//13092013 Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = cad.cargorelet_account_IN_GST;// "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.charge_amount;//04092013 item.charge_addr_comm;
                            acrbatchinput_GL_charge.amount = -item.charge_amount;//04092013item.charge_addr_comm;
                            acrbatchinput_GL_charge.description = "Charge Address Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SD";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else if (item.narrative_line == 90)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Non Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SD";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cad.chartererInv_account;// "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = cad.cargorelet_account_IN_GST;// "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = -item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Non Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SD";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SD";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            acrbatchinput_GL.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL.account = itemChargeType.chartererInv_account;
                                //item.voyage_type.Trim() == "Voyage" ? 
                                //itemChargeType.chartererInv_account : 
                                //itemChargeType.tcrelet_account; //19092013 // 14082013
                            acrbatchinput_GL.dim_1 =
                                acrbatchinput_GL.account.Trim() == "3334" ?
                                profitCentreVessel.agr_rel_value : // 05092013
                                profitCentre.agr_rel_value // 05092013
                                ;//23042013 Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 =profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            //13092013 acrbatchinput_GL.tax_code = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_code = itemChargeType.chartererInv_tax_account;
                                //item.voyage_type.Trim() == "Voyage" ? 
                                //itemChargeType.chartererInv_tax_account : 
                                //itemChargeType.tcrelet_tax_account_singapore;//19092013
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = -item.charge_amount;
                            acrbatchinput_GL.amount = -item.charge_amount;
                            acrbatchinput_GL.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SD";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;
                        }
                    }
                    if (acrbatchinput_AP.amount + totalGL != 0)
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                        }
                        continue;
                    }
                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }

        //no use any more 08 Apr 2013 --------> same with TC RElet event A------------------
        //public void ExecuteCommissionInvoiceVCReletType()
        //{
        //    try
        //    {
        //        m_dataBaseConectivity.InterfaceSqlConnection.Open();
        //        IList invoiceNumbers = new ArrayList();
        //        SqlCommand cmd = new SqlCommand(CommisionInvoiceSQL.GetCommisionInvoiceInvoiceNumberByVCReletTypeAndInvoiceTypeCommissionFromInterfacePending()
        //           , m_dataBaseConectivity.InterfaceSqlConnection);
        //        SqlDataReader rd = cmd.ExecuteReader();
        //        while (rd.Read())
        //        {
        //            invoiceNumbers.Add(rd["invoice_number"].ToString());
        //        }
        //        rd.Close();

        //        IList commissionInvoices = new ArrayList();
        //        foreach (string invoice_number in invoiceNumbers)
        //        {
        //            cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByVCReletTypeAndInvoiceTypeCommissionFromInterfacePendingByInvoiceNumber();
        //            cmd.Parameters.Clear();
        //            cmd.Parameters.Add("invoice_number", SqlDbType.NVarChar).Value = invoice_number;
        //            rd = cmd.ExecuteReader();
        //            CommissionInvoice header = null;
        //            while (rd.Read())
        //            {
        //                if (header == null)
        //                    header = new CommissionInvoice(rd, true);
        //                CommissionInvoice item = new CommissionInvoice(rd, true);
        //                item.Header = header;
        //                header.Items.Add(item);
        //            }
        //            rd.Close();
        //            commissionInvoices.Add(header);
        //        }
        //        foreach (CommissionInvoice ci in commissionInvoices)
        //        {
        //            SupplierCustomer company = m_suppCusService.GetSupplierMapping(ci.company);
        //            ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
        //            m_vesselService.FindVesselByName(ci.vessel_name); // vessel validation inserting if not found------------
        //            ChargeTypeAccountMapping chargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(ci.charge_type);

        //            string alert = "";
        //            if (company.agr_supp_apar_id == "") { alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", company.full_name); };
        //            //if (profitCentre.legal_entity_id.profit_centre_id == 0) { alert += string.Format("- Unable to find Legal entity for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
        //            if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
        //            if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
        //            //ProfitCentre legalEntity = m_profitCentreService.GetProfitCentreByID(profitCentre.legal_entity_id.profit_centre_id);
        //           // Vessel legalEntityVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(legalEntity.profit_centre_id, ci.vessel_name.Trim());
        //           // if (legalEntityVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' for Profit Centre '{1} {2}' \r\n", ci.vessel_name.Trim(), legalEntity.full_name, legalEntity.agr_dim_value); }
        //           // if (legalEntityVessel != null && legalEntityVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}-{1}' \r\n", legalEntityVessel.vessel_name, legalEntityVessel.agr_dim_value); }//alert
        //           // if (legalEntityVessel != null && legalEntityVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", legalEntityVessel.vessel_name); }//alert
        //            Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim());
        //            if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' for Profit Centre '{1} {2}' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
        //            if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
        //            if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
        //            if (chargeType.account == "") { alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'", chargeType.charge_type); } //alert coudnot map account on charge type :---------

        //            if (alert != "")
        //            {
        //                m_alertService.CheckAndUpdateAlert(ci.commission_invoice_id.ToString(), AlertType.SOFTMAR_COMMISSION_INVOICE_VOYAGE_CARGO_RELET, AlertStatus.PENDING,
        //                    string.Format("Failed while interfacing Invoice No.{0}, Invoice Date :{3}, Company Name : {1}, Description : {2}  \r\n", ci.invoice_number, ci.company, ci.charge_description, ci.invoice_date.ToString("dd-MMM-yyyy")) + alert, ci.invoice_number);
        //                continue;
        //            }
        //            else
        //            {
        //                m_alertService.CheckAndUpdateAlert(ci.commission_invoice_id.ToString(), AlertType.SOFTMAR_COMMISSION_INVOICE_VOYAGE_CARGO_RELET, AlertStatus.RESOLVED,
        //                      string.Format("Failed while interfacing Invoice No.{0}, Invoice Date :{3}, Company Name : {1}, Description : {2}  \r\n", ci.invoice_number, ci.company, ci.charge_description, ci.invoice_date.ToString("dd-MMM-yyyy")) + alert, ci.invoice_number);
        //            }

        //            IList acrbatchinputList = new ArrayList();

        //            acrbatchinput acrbatchinput_AP_1 = new acrbatchinput();
        //            acrbatchinput_AP_1.voucher_type = "SB";
        //            acrbatchinput_AP_1.trans_type = "AP";
        //            acrbatchinput_AP_1.client = profitCentre.client;
        //            acrbatchinput_AP_1.apar_type = "P";
        //            acrbatchinput_AP_1.apar_id = company.agr_supp_apar_id;
        //            acrbatchinput_AP_1.account = "";
        //            acrbatchinput_AP_1.dim_1 = profitCentreVessel.agr_rel_value;
        //            acrbatchinput_AP_1.dim_2 = profitCentreVessel.agr_rel_value;
        //            acrbatchinput_AP_1.dim_3 = "";
        //            acrbatchinput_AP_1.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
        //            acrbatchinput_AP_1.dim_5 = profitCentreVessel.agr_dim_value;
        //            acrbatchinput_AP_1.dim_6 = profitCentre.agr_dim_value;
        //            acrbatchinput_AP_1.dim_7 = "";
        //            acrbatchinput_AP_1.tax_code = "0";
        //            acrbatchinput_AP_1.tax_system = "";
        //            acrbatchinput_AP_1.currency = ci.invoice_currency;
        //            acrbatchinput_AP_1.cur_amount = -ci.invoice_amount; //-ci.charge_collect_comm;
        //            acrbatchinput_AP_1.amount = -ci.invoice_amount; //-ci.charge_collect_comm;
        //            acrbatchinput_AP_1.description = ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
        //            acrbatchinput_AP_1.trans_date = ci.invoice_date;
        //            acrbatchinput_AP_1.voucher_date = ci.invoice_date;
        //            acrbatchinput_AP_1.voucher_no = 1;
        //            acrbatchinput_AP_1.ext_inv_ref = ci.invoice_number;
        //            acrbatchinput_AP_1.status = "N";
        //            acrbatchinput_AP_1.due_date = ci.invoice_due_date;
        //            acrbatchinput_AP_1.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
        //            acrbatchinput_AP_1.responsible = "DEV01";
        //            acrbatchinput_AP_1.batch_id = "SB" + DateTime.Now.ToString("ddMMyyyyHHmmss");
        //            acrbatchinput_AP_1.interface_ = "SB";
        //            acrbatchinput_AP_1.sequence_no = GetSequenceRunningNumber();
        //            acrbatchinputList.Add(acrbatchinput_AP_1);

        //            //decimal commisionAmnt = 0;
        //            foreach (CommissionInvoice item in ci.Items)
        //            {
        //                acrbatchinput acrbatchinput_AP_2 = new acrbatchinput();
        //                acrbatchinput_AP_2.voucher_type = "SB";
        //                acrbatchinput_AP_2.trans_type = "GL";
        //                acrbatchinput_AP_2.client = profitCentre.client;
        //                acrbatchinput_AP_2.apar_type = "";
        //                acrbatchinput_AP_2.apar_id = company.agr_supp_apar_id;
        //                acrbatchinput_AP_2.account = chargeType.account;
        //                acrbatchinput_AP_2.dim_1 = "";
        //                acrbatchinput_AP_2.dim_2 = profitCentreVessel.agr_rel_value;
        //                acrbatchinput_AP_2.dim_3 = "";
        //                acrbatchinput_AP_2.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
        //                acrbatchinput_AP_2.dim_5 = profitCentreVessel.agr_dim_value;
        //                acrbatchinput_AP_2.dim_6 = profitCentre.agr_dim_value;
        //                acrbatchinput_AP_2.dim_7 = "";
        //                acrbatchinput_AP_2.tax_code = "0";
        //                acrbatchinput_AP_2.tax_system = "";
        //                acrbatchinput_AP_2.currency = ci.invoice_currency;
        //                acrbatchinput_AP_2.cur_amount = item.GetCommissionAmountVCRelet();// item.charge_addr_comm == 0 ? item.charge_collect_comm : item.charge_addr_comm;//ci.charge_collect_comm;//ci.invoice_amount;
        //                acrbatchinput_AP_2.amount = acrbatchinput_AP_2.cur_amount;// item.charge_addr_comm == 0 ? item.charge_collect_comm : item.charge_addr_comm; //ci.charge_collect_comm;//ci.invoice_amount;
        //                acrbatchinput_AP_2.description = ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
        //                acrbatchinput_AP_2.trans_date = ci.invoice_date;
        //                acrbatchinput_AP_2.voucher_date = ci.invoice_date;
        //                acrbatchinput_AP_2.voucher_no = 1;
        //                acrbatchinput_AP_2.ext_inv_ref = ci.invoice_number;
        //                acrbatchinput_AP_2.status = "N";
        //                acrbatchinput_AP_2.due_date = ci.invoice_due_date;
        //                acrbatchinput_AP_2.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
        //                acrbatchinput_AP_2.responsible = "DEV01";
        //                acrbatchinput_AP_2.batch_id = "SB" + DateTime.Now.ToString("ddMMyyyyHHmmss");
        //                acrbatchinput_AP_2.interface_ = "SB";
        //                acrbatchinput_AP_2.sequence_no = GetSequenceRunningNumber();
        //                acrbatchinputList.Add(acrbatchinput_AP_2);
        //                //commisionAmnt += acrbatchinput_AP_2.amount;
        //            }
        //            //if (acrbatchinput_AP_1.amount + commisionAmnt != 0)
        //            //{
        //            //    throw new Exception("Error not BALANCE invoice :" + ci.invoice_number);
        //            //}

        //            string agrtid = "";
        //            foreach (acrbatchinput acr in acrbatchinputList)
        //            {
        //                m_AcrBatcInputService.Insert(acr);
        //                m_AcrBatcInputService.InsertToInterfaceTable(acr);
        //                agrtid += ";" + acr.agrtid.ToString();
        //            }
        //            //update status-------
        //            foreach (CommissionInvoice item in ci.Items)
        //            {
        //                cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
        //                cmd.Parameters.Clear();
        //                cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
        //                cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
        //                cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
        //                cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid;
        //                cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
        //                cmd.ExecuteNonQuery();
        //            }
        //            //---------------------

        //            //if (!m_AcrBatcInputService.IsExist(acrbatchinput_AP_1)
        //            //        && !m_AcrBatcInputService.IsExist(acrbatchinput_AP_2))
        //            //{
        //            //    m_AcrBatcInputService.Insert(acrbatchinput_AP_1);
        //            //    m_AcrBatcInputService.Insert(acrbatchinput_AP_2);
        //            //    m_AcrBatcInputService.InsertToInterfaceTable(acrbatchinput_AP_1);
        //            //    m_AcrBatcInputService.InsertToInterfaceTable(acrbatchinput_AP_2);
        //            //    //update status-------
        //            //    cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
        //            //    cmd.Parameters.Clear();
        //            //    cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
        //            //    cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
        //            //    cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
        //            //    cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = acrbatchinput_AP_1.agrtid.ToString() +
        //            //        ";" + acrbatchinput_AP_2.agrtid.ToString();
        //            //    cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = ci.commission_invoice_id;
        //            //    cmd.ExecuteNonQuery();
        //            //    //---------------------
        //            //}
        //        }
        //    }
        //    catch (Exception x)
        //    {
        //        LogService.WriteLogException(x);
        //    }
        //    finally
        //    {
        //        m_dataBaseConectivity.SoftmarSqlConnection.Close();
        //    }

        //}

        public void ExecuteFreightHireInvoiceCargoReletChargeDebitIN()
        {
            try
            {
                IList invoiceNumbers = new ArrayList();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand(CommisionInvoiceSQL.GetInvoiceNumberFreightAndHireINChargeDebitFromInterfacePending()
                  , m_dataBaseConectivity.InterfaceSqlConnection);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                    invoiceNumbers.Add(rd["invoice_number"].ToString());
                rd.Close();

                IList FHInvoicesIN = new ArrayList();
                foreach (string invoice_number in invoiceNumbers)
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetFreightAndHireFromInterfacePendingByInvoiceNumber();
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("invoice_number", SqlDbType.NVarChar).Value = invoice_number;
                    rd = cmd.ExecuteReader();
                    CommissionInvoice header = null;
                    while (rd.Read())
                    {
                        if (header == null)
                            header = new CommissionInvoice(rd, true);
                        CommissionInvoice item = new CommissionInvoice(rd, true);
                        item.Header = header;
                        header.Items.Add(item);
                    }
                    rd.Close();
                    FHInvoicesIN.Add(header);
                }
                string prevclient = "";
                int batch = Convert.ToInt16(DateTime.Now.ToString("ss"));

                foreach (CommissionInvoice ci in FHInvoicesIN)
                {
                    SupplierCustomer customer = m_suppCusService.GetCustomerMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    //ResponsibleUser user = m_ResponsibleUserService.GetResponsibleUserByName(ci.raised_to_final_by);
                    m_vesselService.FindVesselByName(ci.vessel_name, ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    string alert = "";
                    if (customer.agr_cust_apar_id == "")
                    {
                        alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", customer.full_name);
                    };
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = ci.voyage_no.ToString().Length >= 8 ? true : 
                        m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" :
                        profitCentreVessel.agr_dim_value, ci.voyage_no);
                    //agldimvalue icVessel = m_agldimvalueService.GetICVesselDimValue(profitCentreVessel == null ? "XXX" : profitCentreVessel.agr_dim_value);
                    //agldimvalue icVoyage = m_agldimvalueService.GetICVoyageDimValue((profitCentreVessel == null ? "XXX" : (profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'))));

                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    //  if (profitCentreVessel != null && icVessel == null) { alert += string.Format("-Unable to find IC Vessel value Code for Vessel '{0}' \r\n", profitCentreVessel.agr_dim_value); } //alert could not  find vessel dim val
                    //  if (profitCentreVessel != null && icVoyage == null) { alert += string.Format("-Unable to find IC Voyage value Code for Voyage '{0}' \r\n", profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0')); } //alert could not  find vessel dim val
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }
                    //if (chargeType.freighthire_account == "") { alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'", chargeType.charge_type); } //alert coudnot map account on charge type :---------

                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.cargorelet_account_IN == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'  \r\n", itemChargeType.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        continue;
                    }
                    IList acrbatchinputList = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();

                    if (prevclient != profitCentre.client)
                        batch++;
                    string batchID = "SD" + DateTime.Now.ToString("ddMMyyyyHHmm") + batch.ToString().PadLeft(2, '0');
                    prevclient = profitCentre.client;

                    acrbatchinput acrbatchinput_AP = new acrbatchinput();
                    acrbatchinput_AP.voucher_type = "SD";
                    acrbatchinput_AP.trans_type = "AR";
                    acrbatchinput_AP.client = profitCentre.client;
                    acrbatchinput_AP.apar_type = "R";
                    acrbatchinput_AP.apar_id = customer.agr_cust_apar_id;
                    acrbatchinput_AP.apar_name = customer.agr_cust_apar_name;
                    acrbatchinput_AP.account = "";
                    acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                    acrbatchinput_AP.dim_2 = "";
                    acrbatchinput_AP.dim_3 = "";
                    acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                    //13092013 ---- TC RELET
                   // acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                   // if (ci.voyage_no.ToString().Length >= 8)//03072013
                   // {
                   //     acrbatchinput_AP.dim_4 = "";
                   // }
                    acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                    acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;
                    acrbatchinput_AP.dim_7 = "";
                    acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                    acrbatchinput_AP.tax_system = "";
                    acrbatchinput_AP.currency = ci.invoice_currency;
                    acrbatchinput_AP.cur_amount = ci.invoice_amount;
                    acrbatchinput_AP.amount = ci.invoice_amount;
                    acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                    acrbatchinput_AP.trans_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                    acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                    acrbatchinput_AP.status = "N";
                    acrbatchinput_AP.due_date = ci.invoice_due_date;
                    acrbatchinput_AP.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                    acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                    acrbatchinput_AP.batch_id = batchID;
                    acrbatchinput_AP.interface_ = "SD";
                    acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                    acrbatchinput_AP.pay_temp_id = "IM";//09062013
                    acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                    acrbatchinputList.Add(acrbatchinput_AP);

                    decimal totalGL = 0;
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        if (item.narrative_line == 70)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Address Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SD";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cad.cargorelet_account_IN;// "5252 ";//13092013 Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = cad.cargorelet_account_IN_GST;// "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.charge_amount;//04092013 item.charge_addr_comm;
                            acrbatchinput_GL_charge.amount = -item.charge_amount;//04092013item.charge_addr_comm;
                            acrbatchinput_GL_charge.description = "Charge Address Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SD";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else if (item.narrative_line == 80)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SD";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cad.cargorelet_account_IN;// "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = cad.cargorelet_account_IN_GST;// "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.charge_amount;//04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = -item.charge_amount;//04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SD";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else if (item.narrative_line == 90)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Non Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SD";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cad.cargorelet_account_IN;// "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = cad.cargorelet_account_IN_GST;// "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = -item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Non Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SD";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SD";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            acrbatchinput_GL.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL.account = itemChargeType.cargorelet_account_IN;
                                //13092013 item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account; // 03072013
                            acrbatchinput_GL.dim_1 =
                                acrbatchinput_GL.account.Trim() == "3334" ?
                                profitCentreVessel.agr_rel_value : // 05092013
                                profitCentre.agr_rel_value // 05092013
                                ;//23042013 Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                               // acrbatchinput_GL.account.Trim() == "3334" ? "" :
                               // profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013 CArina
                            //if (ci.voyage_no.ToString().Length >= 8)//03072013
                           // {
                            //    acrbatchinput_GL.dim_4 = "";
                           // }
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            //13092013 acrbatchinput_GL.tax_code = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_code = itemChargeType.cargorelet_account_IN_GST;
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = -item.charge_amount;
                            acrbatchinput_GL.amount = -item.charge_amount;
                            acrbatchinput_GL.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SD";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;
                        }
                    }
                    if (acrbatchinput_AP.amount + totalGL != 0)
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                        }
                        continue;
                    }
                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }

        public void ExecuteFreightHireInvoiceCargoReletCommissionCreditIN()
        {
            try
            {
                IList invoiceNumbers = new ArrayList();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand(CommisionInvoiceSQL.GetInvoiceNumberFreightAndHireINCommissionCreditFromInterfacePending()
                  , m_dataBaseConectivity.InterfaceSqlConnection);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                    invoiceNumbers.Add(rd["invoice_number"].ToString());
                rd.Close();

                IList FHInvoicesIN = new ArrayList();
                foreach (string invoice_number in invoiceNumbers)
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetFreightAndHireFromCommissionCreditInterfacePendingByInvoiceNumber();
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("invoice_number", SqlDbType.NVarChar).Value = invoice_number;
                    rd = cmd.ExecuteReader();
                    CommissionInvoice header = null;
                    while (rd.Read())
                    {
                        if (header == null)
                            header = new CommissionInvoice(rd, true);
                        CommissionInvoice item = new CommissionInvoice(rd, true);
                        item.Header = header;
                        header.Items.Add(item);
                    }
                    rd.Close();
                    FHInvoicesIN.Add(header);
                }

                string prevclient = "";
                int batch = Convert.ToInt16(DateTime.Now.ToString("ss"));

                foreach (CommissionInvoice ci in FHInvoicesIN)
                {
                    SupplierCustomer supplier = m_suppCusService.GetSupplierMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    //ResponsibleUser user = m_ResponsibleUserService.GetResponsibleUserByName(ci.raised_to_final_by);
                    m_vesselService.FindVesselByName(ci.vessel_name, ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    string alert = "";
                    if (supplier.agr_supp_apar_id == "")
                    {
                        alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", supplier.full_name);
                    };
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = ci.voyage_no.ToString().Length >= 8 ? true :
                        m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" :
                        profitCentreVessel.agr_dim_value, ci.voyage_no);
                    //agldimvalue icVessel = m_agldimvalueService.GetICVesselDimValue(profitCentreVessel == null ? "XXX" : profitCentreVessel.agr_dim_value);
                    //agldimvalue icVoyage = m_agldimvalueService.GetICVoyageDimValue((profitCentreVessel == null ? "XXX" : (profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'))));
                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    //  if (profitCentreVessel != null && icVessel == null) { alert += string.Format("-Unable to find IC Vessel value Code for Vessel '{0}' \r\n", profitCentreVessel.agr_dim_value); } //alert could not  find vessel dim val
                    //  if (profitCentreVessel != null && icVoyage == null) { alert += string.Format("-Unable to find IC Voyage value Code for Voyage '{0}' \r\n", profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0')); } //alert could not  find vessel dim val
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }
                    //if (chargeType.freighthire_account == "") { alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'", chargeType.charge_type); } //alert coudnot map account on charge type :---------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.chartererInv_account == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'  \r\n", itemChargeType.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        continue;
                    }
                    IList acrbatchinputList = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();

                    if (prevclient != profitCentre.client)
                        batch++;
                    string batchID = "SD" + DateTime.Now.ToString("ddMMyyyyHHmm") + batch.ToString().PadLeft(2, '0');
                    prevclient = profitCentre.client;

                    DateTime periodDate = DateTime.Today;// new DateTime(2013, 9, 30);
                    int period = Convert.ToInt32(periodDate.ToString("yyyyMM"));

                    acrbatchinput acrbatchinput_AP = new acrbatchinput();
                    acrbatchinput_AP.voucher_type = "SD";
                    acrbatchinput_AP.trans_type = "AP";
                    acrbatchinput_AP.client = profitCentre.client;
                    acrbatchinput_AP.apar_type = "P";
                    acrbatchinput_AP.apar_id = supplier.agr_supp_apar_id;
                    acrbatchinput_AP.apar_name = supplier.agr_supp_apar_name;
                    acrbatchinput_AP.account = "";
                    acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                    acrbatchinput_AP.dim_2 = "";
                    acrbatchinput_AP.dim_3 = "";
                    acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                    //13092013 ---- TC RELET
                    // acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                    // if (ci.voyage_no.ToString().Length >= 8)//03072013
                    // {
                    //     acrbatchinput_AP.dim_4 = "";
                    // }
                    acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                    acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;
                    acrbatchinput_AP.dim_7 = "";
                    acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                    acrbatchinput_AP.tax_system = "";
                    acrbatchinput_AP.currency = ci.invoice_currency;
                    acrbatchinput_AP.cur_amount = ci.invoice_amount;
                    acrbatchinput_AP.amount = ci.invoice_amount;
                    acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                    acrbatchinput_AP.trans_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                    acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                    acrbatchinput_AP.status = "N";
                    acrbatchinput_AP.due_date = ci.invoice_due_date;
                    acrbatchinput_AP.period = period;// Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                    acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                    acrbatchinput_AP.batch_id = batchID;
                    acrbatchinput_AP.interface_ = "SD";
                    acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                    acrbatchinput_AP.pay_temp_id = "IM";//09062013
                    acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                    acrbatchinputList.Add(acrbatchinput_AP);

                    decimal totalGL = 0;
                    foreach (CommissionInvoice item in ci.Items)
                    {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SD";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = supplier.agr_supp_apar_id;
                            acrbatchinput_GL_charge.apar_name = supplier.agr_supp_apar_name;
                            acrbatchinput_GL_charge.account = cad.cargorelet_account_IN;// "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = cad.cargorelet_account_IN_GST;// "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.GetCommissionCreditTCorVCReletAmountRevision1();//04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = -item.GetCommissionCreditTCorVCReletAmountRevision1();//04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = period;//Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SD";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                    }
                    if (acrbatchinput_AP.amount + totalGL != 0)
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                        }
                        continue;
                    }
                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }

        public void ExecuteFreightHireInvoiceCargoReletChargeCreditOUT()
        {
            try
            {
                IList invoiceNumbers = new ArrayList();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand(CommisionInvoiceSQL.GetInvoiceNumberFreightAndHireOUTFromInterfacePending()
                  , m_dataBaseConectivity.InterfaceSqlConnection);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                    invoiceNumbers.Add(rd["invoice_number"].ToString());
                rd.Close();

                IList FHInvoicesOUT = new ArrayList();
                foreach (string invoice_number in invoiceNumbers)
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetFreightAndHireFromInterfacePendingByInvoiceNumber();
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("invoice_number", SqlDbType.NVarChar).Value = invoice_number;
                    rd = cmd.ExecuteReader();
                    CommissionInvoice header = null;
                    while (rd.Read())
                    {
                        if (header == null)
                            header = new CommissionInvoice(rd, true);
                        CommissionInvoice item = new CommissionInvoice(rd, true);
                        item.Header = header;
                        header.Items.Add(item);
                    }
                    rd.Close();
                    FHInvoicesOUT.Add(header);
                }

                string prevclient = "";
                int batch = Convert.ToInt16(DateTime.Now.ToString("ss"));

                foreach (CommissionInvoice ci in FHInvoicesOUT)
                {
                    SupplierCustomer supplier = m_suppCusService.GetSupplierMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    //ResponsibleUser user = m_ResponsibleUserService.GetResponsibleUserByName(ci.raised_to_final_by);
                    m_vesselService.FindVesselByName(ci.vessel_name, ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    string alert = "";
                    if (supplier.agr_supp_apar_id == "")
                    {
                        alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", supplier.full_name);
                    };
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = ci.voyage_no.ToString().Length >= 8 ? true : m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);

                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }

                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.cargorelet_account_OUT_SG == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map CRelet Out for Charge Type '{0}' \r\n", item.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        continue;
                    }

                    IList acrbatchinputList = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();

                    if (prevclient != profitCentre.client)
                        batch++;
                    string batchID = "SC" + DateTime.Now.ToString("ddMMyyyyHHmm") + batch.ToString().PadLeft(2, '0');
                    prevclient = profitCentre.client;

                    acrbatchinput acrbatchinput_AP = new acrbatchinput();
                    acrbatchinput_AP.voucher_type = "SC";
                    acrbatchinput_AP.trans_type = "AP";
                    acrbatchinput_AP.client = profitCentre.client;
                    acrbatchinput_AP.apar_type = "P";
                    acrbatchinput_AP.apar_id = supplier.agr_supp_apar_id;
                    acrbatchinput_AP.apar_name = supplier.agr_supp_apar_name;
                    acrbatchinput_AP.account = "";
                    acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                    acrbatchinput_AP.dim_2 = "";
                    acrbatchinput_AP.dim_3 = "";
                    acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                    //28082013 if (ci.voyage_no.ToString().Length >= 8)//03072013
                    //28082013 {
                    //28082013     acrbatchinput_AP.dim_4 = "";
                    //28082013 }
                    acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                    acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;
                    acrbatchinput_AP.dim_7 = "";
                    acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                    acrbatchinput_AP.tax_system = "";
                    acrbatchinput_AP.currency = ci.invoice_currency;
                    acrbatchinput_AP.cur_amount = -ci.invoice_amount; // minus 25032014
                    acrbatchinput_AP.amount = -ci.invoice_amount; // minus 25032014
                    acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                    acrbatchinput_AP.trans_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_date = ci.invoice_date.Date;
                    acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                    acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                    acrbatchinput_AP.status = "N";
                    acrbatchinput_AP.due_date = ci.invoice_due_date;
                    acrbatchinput_AP.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                    acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                    acrbatchinput_AP.batch_id = batchID;
                    acrbatchinput_AP.interface_ = "SC";
                    acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                    acrbatchinput_AP.pay_temp_id = "IM";//09062013
                    acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                    acrbatchinputList.Add(acrbatchinput_AP);

                    decimal totalGL = 0;
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        if (item.narrative_line == 70)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Address Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SC";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = supplier.agr_supp_apar_id;
                            acrbatchinput_GL_charge.apar_name = supplier.agr_supp_apar_name;
                            acrbatchinput_GL_charge.account = cad.cargorelet_account_OUT_SG; //28082013 "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code =
                                supplier.country_code_sup == "SG" ?
                                cad.cargorelet_account_OUT_SG_GST :
                                cad.cargorelet_account_OUT_Ovs_GST;
                            //28082013 "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.charge_amount;//positive 25032014 //04092013 item.charge_addr_comm;
                            acrbatchinput_GL_charge.amount = item.charge_amount;//positive 25032014  //04092013 item.charge_addr_comm;
                            acrbatchinput_GL_charge.description = "Charge Address Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SC";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else if (item.narrative_line == 80)
                        {
                            ChargeTypeAccountMapping cncc = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SC";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = supplier.agr_supp_apar_id;
                            acrbatchinput_GL_charge.apar_name = supplier.agr_supp_apar_name;
                            acrbatchinput_GL_charge.account = cncc.cargorelet_account_OUT_SG;//28082013 "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code =
                                 supplier.country_code_sup == "SG" ?
                                cncc.cargorelet_account_OUT_SG_GST :
                                cncc.cargorelet_account_OUT_Ovs_GST;
                            ;//"ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.charge_amount;//positive 25032014  //04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = item.charge_amount;//positive 25032014  //04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SC";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else if (item.narrative_line == 90)
                        {
                            ChargeTypeAccountMapping cncc = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Non Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SC";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.apar_id = supplier.agr_supp_apar_id;
                            acrbatchinput_GL_charge.apar_name = supplier.agr_supp_apar_name;
                            acrbatchinput_GL_charge.account = cncc.cargorelet_account_OUT_SG;//28082013 "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code =
                                 supplier.country_code_sup == "SG" ?
                                cncc.cargorelet_account_OUT_SG_GST :
                                cncc.cargorelet_account_OUT_Ovs_GST;
                            ;//"ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.charge_amount;//positive 25032014 //04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = item.charge_amount;//positive 25032014 //04092013 item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Non Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SC";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;
                        }
                        else
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SC";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            acrbatchinput_GL.apar_id = supplier.agr_supp_apar_id;
                            acrbatchinput_GL.apar_name = supplier.agr_supp_apar_name;
                            acrbatchinput_GL.account = itemChargeType.cargorelet_account_OUT_SG;
                            //13092013
                                //item.voyage_no.ToString().Length >= 8 ?
                                //itemChargeType.cargorelet_account_OUT_SG
                                //: itemChargeType.chartererInv_account; // 03072013
                            acrbatchinput_GL.dim_1 =
                                acrbatchinput_GL.account.Trim() == "3334" ?
                                profitCentre.agr_rel_value :
                                profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//30092013
                            //13092013
                               // itemChargeType.chartererInv_account.Trim() == "3334" ? "" :
                               // profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013CArina
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            acrbatchinput_GL.tax_code =
                                supplier.country_code_sup == "SG" ?
                                itemChargeType.cargorelet_account_OUT_SG_GST :
                                itemChargeType.cargorelet_account_OUT_Ovs_GST;
                            //itemChargeType.freighthire_tax_account;// "";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = item.charge_amount;//positive 25032014 
                            acrbatchinput_GL.amount = item.charge_amount;//positive 25032014 
                            acrbatchinput_GL.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(DateTime.Today.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SC";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;
                        }

                    }
                    if (acrbatchinput_AP.amount + totalGL != 0)
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                        }
                        continue;
                    }
                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public void ExecuteInvoiceProformaCommissionCredit(CommissionInvoice pf)
        {
            //int test = 0;
            try
            {
                IList invoiceNumbers = new ArrayList();
                if (pf == null)
                {
                    invoiceNumbers = GetAllProformaCommissionCreditPendingLastMOnthPeriod(); //GetAllProformaPendingLastMOnthPeriod(new DateTime(2013, 8, 1)); // 
                }
                else
                {
                    InvoiceProforma ps = new InvoiceProforma(pf);
                    invoiceNumbers.Add(ps);
                }
                //IList invoiceNumbers = GetAllProformaCommissionCreditPendingLastMOnthPeriod(new DateTime(2013, 7, 1));
                //IList invoiceNumbers = GetAllProformaPending();
                IList proformaInvoices = new ArrayList();
                foreach (InvoiceProforma ip in invoiceNumbers)
                {
                    CommissionInvoice ci = null;
                    IList items = GetProformaItem(ip);
                    if (ci == null)
                    {
                        ci = (CommissionInvoice)items[0];
                        ci.Header = (CommissionInvoice)items[0];
                        ci.Items = items;
                        foreach (CommissionInvoice itm in items)
                            itm.Header = ci.Header;
                    }
                    proformaInvoices.Add(ci);
                }
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand("", m_dataBaseConectivity.InterfaceSqlConnection);
                //DateTime today = m_lastDateProforma;//DateTime.Today;
                DateTime lastDateInMonth = m_currentPeriodProforma;
                   // new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));//new DateTime(2013, 8, 31);//
                DateTime NextDateInMonth = lastDateInMonth.AddDays(1);

                string prevProfitCentreClient = "";
                DateTime prevInvoiceDate = DateTime.Now;

                foreach (CommissionInvoice ci in proformaInvoices)
                {
                    SupplierCustomer supplier = m_suppCusService.GetSupplierMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    m_vesselService.FindVesselByName(ci.vessel_name, ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    string alert = "";
                    if (supplier.agr_supp_apar_id == "")
                    {
                        alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", supplier.full_name);
                    };
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = ci.voyage_no.ToString().Length >= 8 ? true : m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);
                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Collect Comm");// GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.chartererInv_account == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'  \r\n", itemChargeType.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        continue;
                    }

                    IList acrbatchinputList = new ArrayList();
                    IList acrbatchinputListReverse = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();

                    if (prevProfitCentreClient != profitCentre.client)
                    {
                        batchIDCountProforma++;
                        batchIDRevCountProforma++;
                    }
                    else if (prevInvoiceDate != ci.GetInvoiceDate())
                    {
                        batchIDCountProforma++;
                        batchIDRevCountProforma++;
                    }
                    string batchID = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchIDCountProforma.ToString().PadLeft(6, '0');
                    string batchIDReverse = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchIDRevCountProforma.ToString().PadLeft(6, '0');
                    prevProfitCentreClient = profitCentre.client;
                    prevInvoiceDate = ci.GetInvoiceDate();

                    if (supplier.interco)
                    {
                        supplier.ProfitCentre = m_profitCentreService.GetProfitCentreByID(supplier.ProfitCentre.profit_centre_id); //ProfitCentre interco
                        acrbatchinput acrbatchinput_AP = new acrbatchinput();
                        acrbatchinput_AP.client = profitCentre.client;////supplier.ProfitCentre.client;
                        acrbatchinput_AP.voucher_type = "SH";
                        acrbatchinput_AP.trans_type = "GL";
                        acrbatchinput_AP.apar_type = "R";
                        acrbatchinput_AP.account = "3302";
                        acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                        acrbatchinput_AP.dim_2 = "";
                        acrbatchinput_AP.dim_3 = "";
                        acrbatchinput_AP.dim_4 = ci.voyage_type == "Cargo Relet" ? profitCentreVessel.agr_dim_value + "-V000" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                        acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;// supplier.ProfitCentre.agr_dim_value;
                        acrbatchinput_AP.dim_7 = "";
                        acrbatchinput_AP.tax_code = "";
                        acrbatchinput_AP.tax_system = "";
                        acrbatchinput_AP.currency = ci.invoice_currency;
                        acrbatchinput_AP.cur_amount = -ci.invoice_amount;
                        acrbatchinput_AP.amount = -ci.invoice_amount;
                        acrbatchinput_AP.description = ci.invoice_number + ":" + ci.charge_description + ci.raised_to_final_by;
                        acrbatchinput_AP.trans_date = DateTime.Today;
                        acrbatchinput_AP.voucher_date = ci.invoice_date;
                        acrbatchinput_AP.voucher_no = voucherNumber;
                        acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                        acrbatchinput_AP.status = "N";
                        acrbatchinput_AP.due_date = ci.invoice_due_date;
                        acrbatchinput_AP.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP.responsible = "DEV01";
                        acrbatchinput_AP.batch_id = batchID;
                        acrbatchinput_AP.interface_ = "SH";
                        acrbatchinput_AP.disc_date = DateTime.Now;
                        acrbatchinput_AP.pay_temp_id = "IM";
                        acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                        acrbatchinputList.Add(acrbatchinput_AP);

                        acrbatchinput acrbatchinput_AP_reverse = acrbatchinput_AP.Duplicate();
                        acrbatchinput_AP_reverse.amount = -acrbatchinput_AP_reverse.amount;
                        acrbatchinput_AP_reverse.cur_amount = -acrbatchinput_AP_reverse.cur_amount;
                        acrbatchinput_AP_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP_reverse.batch_id = batchIDReverse;
                        acrbatchinput_AP_reverse.trans_date = NextDateInMonth;
                        acrbatchinputListReverse.Add(acrbatchinput_AP_reverse);

                        //testing production
                        //if (acrbatchinput_AP.dim_6.Trim().Substring(0, 1) != "5")
                           // continue;
                       
                        decimal totalGL = 0;
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SH";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client; //supplier.ProfitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.account = "5103";// item.voyage_type == "Cargo Relet" ? cad.cargorelet_account_IN : cad.chartererInv_account; //"5101";
                            acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//01102013 supplier.ProfitCentre.agr_rel_value;
                            acrbatchinput_GL_charge.dim_2 = "";// supplier.ProfitCentre.expense_account;
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = item.voyage_type == "Cargo Relet" ? profitCentreVessel.agr_dim_value + "-V000" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;//01102013 supplier.ProfitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";//01102013 profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.tax_code = "ZO";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.GetCommissionCreditTCorVCReletAmountRevision1();
                            acrbatchinput_GL_charge.amount = item.GetCommissionCreditTCorVCReletAmountRevision1();
                            acrbatchinput_GL_charge.description = "Charge Collect Comm";
                            acrbatchinput_GL_charge.trans_date = DateTime.Today;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SH";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;
                            acrbatchinput_GL_charge.pay_temp_id = "IM";
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();

                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;

                            acrbatchinput acrbatchinput_GL_charge_reverse = acrbatchinput_GL_charge.Duplicate();
                            acrbatchinput_GL_charge_reverse.cur_amount = -acrbatchinput_GL_charge_reverse.cur_amount;
                            acrbatchinput_GL_charge_reverse.amount = -acrbatchinput_GL_charge_reverse.amount;
                            acrbatchinput_GL_charge_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_charge_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_charge_reverse);
                        }
                        if (acrbatchinput_AP.amount + totalGL != 0)
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                    }
                    else
                    {
                        ProfitCentre legalEntity = m_profitCentreService.GetProfitCentreByID(profitCentre.CommissionManager.profit_centre_id);
                        acrbatchinput acrbatchinput_AP = new acrbatchinput();
                        acrbatchinput_AP.client = profitCentre.client;
                        acrbatchinput_AP.voucher_type = "SH";
                        acrbatchinput_AP.trans_type = "GL";
                        acrbatchinput_AP.apar_type = "R";
                        acrbatchinput_AP.account = "3302";
                        acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                        acrbatchinput_AP.dim_2 = "";
                        acrbatchinput_AP.dim_3 = "";
                        acrbatchinput_AP.dim_4 = ci.voyage_type == "Cargo Relet" ? profitCentreVessel.agr_dim_value + "-V000" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                        acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;
                        acrbatchinput_AP.dim_7 = "";
                        acrbatchinput_AP.tax_code = "";
                        acrbatchinput_AP.tax_system = "";
                        acrbatchinput_AP.currency = ci.invoice_currency;
                        acrbatchinput_AP.cur_amount = -ci.invoice_amount;
                        acrbatchinput_AP.amount = -ci.invoice_amount;
                        acrbatchinput_AP.description = ci.invoice_number + ":" + ci.charge_description + ci.raised_to_final_by;
                        acrbatchinput_AP.trans_date = DateTime.Today;
                        acrbatchinput_AP.voucher_date = ci.invoice_date;
                        acrbatchinput_AP.voucher_no = voucherNumber;
                        acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                        acrbatchinput_AP.status = "N";
                        acrbatchinput_AP.due_date = ci.invoice_due_date;
                        acrbatchinput_AP.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP.responsible = "DEV01";
                        acrbatchinput_AP.batch_id = batchID;
                        acrbatchinput_AP.interface_ = "SH";
                        acrbatchinput_AP.disc_date = DateTime.Now;
                        acrbatchinput_AP.pay_temp_id = "IM";
                        acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                        acrbatchinputList.Add(acrbatchinput_AP);

                        acrbatchinput acrbatchinput_AP_reverse = acrbatchinput_AP.Duplicate();
                        acrbatchinput_AP_reverse.amount = -acrbatchinput_AP_reverse.amount;
                        acrbatchinput_AP_reverse.cur_amount = -acrbatchinput_AP_reverse.cur_amount;
                        acrbatchinput_AP_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP_reverse.batch_id = batchIDReverse;
                        acrbatchinput_AP_reverse.trans_date = NextDateInMonth;
                        acrbatchinputListReverse.Add(acrbatchinput_AP_reverse);

                        //testing production
                        //if (acrbatchinput_AP.dim_6.Trim().Substring(0, 1) != "5")
                           // continue;

                        decimal totalGL = 0;
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            //ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SH";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            acrbatchinput_GL_charge.account = "5101"; //item.voyage_type == "Cargo Relet" ? cad.cargorelet_account_IN : cad.chartererInv_account; 
                            acrbatchinput_GL_charge.dim_1 = legalEntity.agr_rel_value;
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = item.voyage_type == "Cargo Relet" ? profitCentreVessel.agr_dim_value + "-V000" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = "0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.GetCommissionCreditTCorVCReletAmountRevision1();
                            acrbatchinput_GL_charge.amount = item.GetCommissionCreditTCorVCReletAmountRevision1();
                            acrbatchinput_GL_charge.description = "Charge Collect Comm";
                            acrbatchinput_GL_charge.trans_date = DateTime.Today;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SH";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;
                            acrbatchinput_GL_charge.pay_temp_id = "IM";
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();

                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;

                            acrbatchinput acrbatchinput_GL_charge_reverse = acrbatchinput_GL_charge.Duplicate();
                            acrbatchinput_GL_charge_reverse.cur_amount = -acrbatchinput_GL_charge_reverse.cur_amount;
                            acrbatchinput_GL_charge_reverse.amount = -acrbatchinput_GL_charge_reverse.amount;
                            acrbatchinput_GL_charge_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_charge_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_charge_reverse);
                        }
                        if (acrbatchinput_AP.amount + totalGL != 0)
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                    }
                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //disable----------production 03092013
                    //foreach (acrbatchinput acr in acrbatchinputListReverse)
                    //{
                    //    m_AcrBatcInputService.Insert(acr);
                    //    m_AcrBatcInputService.InsertToInterfaceTable(acr);
                    //    agrtid += ";" + acr.agrtid.ToString();
                    //}
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }

        }
        public void ExecuteInvoiceProformaChargeDebit(CommissionInvoice pf)
        {
            try
            {
                IList invoiceNumbers = new ArrayList();
                if (pf == null)
                {
                    invoiceNumbers = GetAllProformaChargeDebitPendingLastMOnthPeriod(); //GetAllProformaPendingLastMOnthPeriod(new DateTime(2013, 8, 1)); // 
                }
                else
                {
                    InvoiceProforma ps = new InvoiceProforma(pf);
                    invoiceNumbers.Add(ps);
                }
                //IList invoiceNumbers = GetAllProformaChargeDebitPendingLastMOnthPeriod(); //GetAllProformaPendingLastMOnthPeriod(new DateTime(2013, 8, 1)); // 
                //IList invoiceNumbers = GetAllProformaChargeDebitPendingLastMOnthPeriod(new DateTime(2013, 7, 1));
                //IList invoiceNumbers = GetAllProformaPending();
                IList proformaInvoices = new ArrayList();
                foreach (InvoiceProforma ip in invoiceNumbers)
                {
                    CommissionInvoice ci = null;
                    IList items = GetProformaItem(ip);
                    if (ci == null)
                    {
                        ci = (CommissionInvoice)items[0];
                        ci.Header = (CommissionInvoice)items[0];
                        ci.Items = items;
                    }
                    proformaInvoices.Add(ci);
                }
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand("", m_dataBaseConectivity.InterfaceSqlConnection);
                //DateTime today = m_lastDateProforma;//DateTime.Today;
                DateTime lastDateInMonth = m_currentPeriodProforma;
                    //new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));
                //DateTime lastDateInMonth = new DateTime(2013,7,31);
                DateTime NextDateInMonth = lastDateInMonth.AddDays(1);

                //int batchNumber = Convert.ToInt32(DateTime.Now.ToString("HHmmss"));
                string prevProfitCentreClient = "";
                DateTime prevInvoiceDate = DateTime.Now;
              //  int batchIDCount = 0;// Convert.ToInt16(DateTime.Now.ToString("ss"));
              //  int batchIDRevCount = batchIDCount + 50;

                foreach (CommissionInvoice ci in proformaInvoices)
                {
                    //SupplierCustomer customer = m_suppCusService.GetCustomerMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    m_vesselService.FindVesselByName(ci.vessel_name,ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    string alert = "";
                    //if (customer.agr_cust_apar_id == "")
                    //{
                    //    alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", customer.full_name);
                    //};
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = ci.voyage_no.ToString().Length >= 8 ? true : m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);
                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.chartererInv_account == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'  \r\n", itemChargeType.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        continue;
                    }
                    IList acrbatchinputList = new ArrayList();
                    IList acrbatchinputListReverse = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();

                    if (prevProfitCentreClient != profitCentre.client)
                    {
                        batchIDCountProforma++;
                        batchIDRevCountProforma++;
                    }
                    else if (prevInvoiceDate != ci.GetInvoiceDate())
                    {
                        batchIDCountProforma++;
                        batchIDRevCountProforma++;
                    }
                    string batchID = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchIDCountProforma.ToString().PadLeft(6, '0');
                    string batchIDReverse = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchIDRevCountProforma.ToString().PadLeft(6, '0');
                    prevProfitCentreClient = profitCentre.client;
                    prevInvoiceDate = ci.GetInvoiceDate();
                    //if (prevclient != "")
                    //{
                    //    if (profitCentre.client != prevclient)
                    //    {
                    //        if (prevbatchID == batchID)
                    //            batchID = "SH" + DateTime.Now.Add(new TimeSpan(0, 0, 1)).ToString("ddMMyyyyHHmmss");
                    //    }
                    //}
                    //prevbatchID = batchID;
                    //prevclient = profitCentre.client;
                    acrbatchinput acrbatchinput_AP = new acrbatchinput();
                    acrbatchinput_AP.voucher_type = "SH";
                    acrbatchinput_AP.trans_type = "GL";
                    acrbatchinput_AP.client = profitCentre.client;
                    acrbatchinput_AP.apar_type = "R";
                    //acrbatchinput_AP.apar_id = customer.agr_cust_apar_id;
                    //acrbatchinput_AP.apar_name = customer.agr_cust_apar_name;
                    acrbatchinput_AP.account = "2201";//12072013 "3302";
                    acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                    acrbatchinput_AP.dim_2 = "";
                    acrbatchinput_AP.dim_3 = "";
                    if (ci.voyage_type == "Cargo Relet")//03072013
                        acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                    else 
                        acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                    acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                    acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;
                    acrbatchinput_AP.dim_7 = "";
                    acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                    acrbatchinput_AP.tax_system = "";
                    acrbatchinput_AP.currency = ci.invoice_currency;
                    acrbatchinput_AP.cur_amount = ci.invoice_amount; //DEBIT
                    acrbatchinput_AP.amount = ci.invoice_amount;
                    acrbatchinput_AP.description = ci.invoice_number + ":" + ci.charge_description + ci.raised_to_final_by;
                    acrbatchinput_AP.trans_date = DateTime.Today;// ci.invoice_date;
                    acrbatchinput_AP.voucher_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                    acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                    acrbatchinput_AP.status = "N";
                    acrbatchinput_AP.due_date = ci.invoice_due_date;
                    acrbatchinput_AP.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                    acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                    acrbatchinput_AP.batch_id = batchID;
                    acrbatchinput_AP.interface_ = "SH";
                    acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                    acrbatchinput_AP.pay_temp_id = "IM";//09062013
                    acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                    acrbatchinputList.Add(acrbatchinput_AP);
                    
                    acrbatchinput acrbatchinput_AP_reverse = acrbatchinput_AP.Duplicate();
                    acrbatchinput_AP_reverse.amount = -acrbatchinput_AP_reverse.amount;
                    acrbatchinput_AP_reverse.cur_amount = -acrbatchinput_AP_reverse.cur_amount;
                    acrbatchinput_AP_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                    acrbatchinput_AP_reverse.batch_id = batchIDReverse;
                    acrbatchinput_AP_reverse.trans_date = NextDateInMonth;
                    acrbatchinputListReverse.Add(acrbatchinput_AP_reverse);

                    //testing production
                    //if (acrbatchinput_AP.dim_6.Trim().Substring(0, 1) != "5")
                       // continue;

                    decimal totalGL = 0;
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        if (item.narrative_line == 70)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Address Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SH";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            //acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            //acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = item.voyage_type == "Cargo Relet" ? cad.cargorelet_account_IN : cad.chartererInv_account;//"5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentre.agr_rel_value; //23092013 profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            if (ci.voyage_type == "Cargo Relet")//03072013
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                            else
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.charge_amount;//04092013 item.charge_addr_comm;
                            acrbatchinput_GL_charge.amount = -item.charge_amount;//04092013item.charge_addr_comm;
                            acrbatchinput_GL_charge.description = "Charge Address Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = DateTime.Today;// ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SH";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;

                            acrbatchinput acrbatchinput_GL_charge_reverse = acrbatchinput_GL_charge.Duplicate();
                            acrbatchinput_GL_charge_reverse.cur_amount = -acrbatchinput_GL_charge_reverse.cur_amount;
                            acrbatchinput_GL_charge_reverse.amount = -acrbatchinput_GL_charge_reverse.amount;
                            acrbatchinput_GL_charge_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_charge_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_charge_reverse);
                        }                       
                        else if (item.narrative_line == 90)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Non Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SH";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            //acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            //acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = item.voyage_type == "Cargo Relet" ? cad.cargorelet_account_IN : cad.chartererInv_account;//acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentre.agr_rel_value; //23092013 profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            if (ci.voyage_type == "Cargo Relet")//03072013
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                            else
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = -item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = -item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Non Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = DateTime.Today;// ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SH";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;

                            acrbatchinput acrbatchinput_GL_charge_reverse = acrbatchinput_GL_charge.Duplicate();
                            acrbatchinput_GL_charge_reverse.cur_amount = -acrbatchinput_GL_charge_reverse.cur_amount;
                            acrbatchinput_GL_charge_reverse.amount = -acrbatchinput_GL_charge_reverse.amount;
                            acrbatchinput_GL_charge_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_charge_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_charge_reverse);
                        }
                        else
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SH";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            //acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            //acrbatchinput_GL.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL.account = item.voyage_type == "Cargo Relet" ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account;//
                            //acrbatchinput_GL.account = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account; // 03072013
                            acrbatchinput_GL.dim_1 = profitCentre.agr_rel_value; //23092013 
                                //acrbatchinput_GL.account.Trim() == "3334" ?
                                //profitCentreVessel.agr_rel_value : // 05092013
                                //profitCentre.agr_rel_value // 05092013
                                //;//23042013 Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            if (ci.voyage_type == "Cargo Relet")//03072013
                                acrbatchinput_GL.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                            else
                                acrbatchinput_GL.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            //acrbatchinput_GL.dim_4 =
                            //    acrbatchinput_GL.account.Trim() == "3334" ? "" :
                            //    profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013 CArina
                            //if (ci.voyage_no.ToString().Length >= 8)//03072013
                            //{
                            //    acrbatchinput_GL.dim_4 = "";
                            //}
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            acrbatchinput_GL.tax_code = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = -item.charge_amount;
                            acrbatchinput_GL.amount = -item.charge_amount;
                            acrbatchinput_GL.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = DateTime.Today;// ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SH";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;

                            acrbatchinput acrbatchinput_GL_reverse = acrbatchinput_GL.Duplicate();
                            acrbatchinput_GL_reverse.cur_amount = -acrbatchinput_GL_reverse.cur_amount;
                            acrbatchinput_GL_reverse.amount = -acrbatchinput_GL_reverse.amount;
                            acrbatchinput_GL_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_reverse);
                        }
                    }
                    if (acrbatchinput_AP.amount + totalGL != 0)
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                        }
                        continue;
                    }
                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //disable----------production 03092013
                    //foreach (acrbatchinput acr in acrbatchinputListReverse)
                    //{
                    //    m_AcrBatcInputService.Insert(acr);
                    //    m_AcrBatcInputService.InsertToInterfaceTable(acr);
                    //    agrtid += ";" + acr.agrtid.ToString();
                    //}
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }

        }
        public void ExecuteInvoiceProformaChargeCredit(CommissionInvoice pf) //Cargo RELET.....
        {
            try
            {
                IList invoiceNumbers = new ArrayList();
                if (pf == null)
                {
                    invoiceNumbers = GetAllProformaChargeCreditPendingLastMOnthPeriod(); //GetAllProformaPendingLastMOnthPeriod(new DateTime(2013, 8, 1)); // 
                }
                else
                {
                    InvoiceProforma ps = new InvoiceProforma(pf);
                    invoiceNumbers.Add(ps);
                }

                IList proformaInvoices = new ArrayList();
                foreach (InvoiceProforma ip in invoiceNumbers)
                {
                    CommissionInvoice ci = null;
                    IList items = GetProformaItem(ip);
                    if (ci == null)
                    {
                        ci = (CommissionInvoice)items[0];
                        ci.Header = (CommissionInvoice)items[0];
                        ci.Items = items;
                    }
                    proformaInvoices.Add(ci);
                }
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand("", m_dataBaseConectivity.InterfaceSqlConnection);
                //DateTime today = m_lastDateProforma;// DateTime.Today;
                DateTime lastDateInMonth = m_currentPeriodProforma;
                    //new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));//new DateTime(2013, 8, 31);//
                DateTime NextDateInMonth = lastDateInMonth.AddDays(1);

                //int batchNumber = Convert.ToInt32(DateTime.Now.ToString("HHmmss"));
                string prevProfitCentreClient = "";
                DateTime prevInvoiceDate = DateTime.Now;
               // int batchIDCount = 0;// Convert.ToInt16(DateTime.Now.ToString("ss"));
               // int batchIDRevCount = batchIDCount + 50;

                foreach (CommissionInvoice ci in proformaInvoices)
                {
                    //SupplierCustomer customer = m_suppCusService.GetCustomerMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    m_vesselService.FindVesselByName(ci.vessel_name,ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    string alert = "";
                    //if (customer.agr_cust_apar_id == "")
                    //{
                    //    alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", customer.full_name);
                    //};
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = ci.voyage_no.ToString().Length >= 8 ? true : m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);
                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.cargorelet_account_OUT_SG == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'  \r\n", itemChargeType.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        continue;
                    }
                    IList acrbatchinputList = new ArrayList();
                    IList acrbatchinputListReverse = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();

                    if(prevProfitCentreClient != profitCentre.client)
                    {
                        batchIDCountProforma++;
                        batchIDRevCountProforma++;
                    }
                    else if (prevInvoiceDate != ci.GetInvoiceDate())
                    {
                        batchIDCountProforma++;
                        batchIDRevCountProforma++;
                    }
                    string batchID = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchIDCountProforma.ToString().PadLeft(6, '0');
                    string batchIDReverse = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchIDRevCountProforma.ToString().PadLeft(6, '0');
                    prevProfitCentreClient = profitCentre.client;
                    prevInvoiceDate = ci.GetInvoiceDate();

                    acrbatchinput acrbatchinput_AP = new acrbatchinput();
                    acrbatchinput_AP.voucher_type = "SH";
                    acrbatchinput_AP.trans_type = "GL";
                    acrbatchinput_AP.client = profitCentre.client;
                    acrbatchinput_AP.apar_type = "R";
                    acrbatchinput_AP.account = "2201";//12072013 "3302";
                    acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                    acrbatchinput_AP.dim_2 = "";
                    acrbatchinput_AP.dim_3 = "";
                    acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                    //acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                    //if (ci.voyage_no.ToString().Length >= 8)//03072013
                   // {
                   //     acrbatchinput_AP.dim_4 = "";
                   // }
                    acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                    acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;
                    acrbatchinput_AP.dim_7 = "";
                    acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                    acrbatchinput_AP.tax_system = "";
                    acrbatchinput_AP.currency = ci.invoice_currency;
                    acrbatchinput_AP.cur_amount = -ci.invoice_amount;
                    acrbatchinput_AP.amount = -ci.invoice_amount;
                    acrbatchinput_AP.description = ci.invoice_number + ":" + ci.charge_description + ci.raised_to_final_by;
                    acrbatchinput_AP.trans_date = DateTime.Today;// ci.invoice_date;
                    acrbatchinput_AP.voucher_date = ci.invoice_date;
                    acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                    acrbatchinput_AP.ext_inv_ref = ci.invoice_number;
                    acrbatchinput_AP.status = "N";
                    acrbatchinput_AP.due_date = ci.invoice_due_date;
                    acrbatchinput_AP.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                    acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                    acrbatchinput_AP.batch_id = batchID;
                    acrbatchinput_AP.interface_ = "SH";
                    acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                    acrbatchinput_AP.pay_temp_id = "IM";//09062013
                    acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                    acrbatchinputList.Add(acrbatchinput_AP);

                    acrbatchinput acrbatchinput_AP_reverse = acrbatchinput_AP.Duplicate();
                    acrbatchinput_AP_reverse.amount = -acrbatchinput_AP_reverse.amount;
                    acrbatchinput_AP_reverse.cur_amount = -acrbatchinput_AP_reverse.cur_amount;
                    acrbatchinput_AP_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                    acrbatchinput_AP_reverse.batch_id = batchIDReverse;
                    acrbatchinput_AP_reverse.trans_date = NextDateInMonth;
                    acrbatchinputListReverse.Add(acrbatchinput_AP_reverse);

                    //testing production---------- 
                    //if (acrbatchinput_AP.dim_6.Trim().Substring(0, 1) != "5")
                        ///continue;

                    decimal totalGL = 0;
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        if (item.narrative_line == 70)
                        {
                            ChargeTypeAccountMapping cad = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Address Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SH";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            //acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            //acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cad.cargorelet_account_OUT_SG;// "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentre.agr_rel_value; //23092013 profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                           // acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.charge_amount;//04092013 item.charge_addr_comm;
                            acrbatchinput_GL_charge.amount = item.charge_amount;//04092013item.charge_addr_comm;
                            acrbatchinput_GL_charge.description = "Charge Address Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = DateTime.Today;// ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SH";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;

                            acrbatchinput acrbatchinput_GL_charge_reverse = acrbatchinput_GL_charge.Duplicate();
                            acrbatchinput_GL_charge_reverse.cur_amount = -acrbatchinput_GL_charge_reverse.cur_amount;
                            acrbatchinput_GL_charge_reverse.amount = -acrbatchinput_GL_charge_reverse.amount;
                            acrbatchinput_GL_charge_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_charge_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_charge_reverse);
                        }
                        else if (item.narrative_line == 80)
                        {
                            ChargeTypeAccountMapping cncc = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SH";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            //acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            //acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cncc.cargorelet_account_OUT_SG;// "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentre.agr_rel_value; //23092013 profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                            //  acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = DateTime.Today;// ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SH";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;

                            acrbatchinput acrbatchinput_GL_charge_reverse = acrbatchinput_GL_charge.Duplicate();
                            acrbatchinput_GL_charge_reverse.cur_amount = -acrbatchinput_GL_charge_reverse.cur_amount;
                            acrbatchinput_GL_charge_reverse.amount = -acrbatchinput_GL_charge_reverse.amount;
                            acrbatchinput_GL_charge_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_charge_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_charge_reverse);
                        }
                        else if (item.narrative_line == 90)
                        {
                            ChargeTypeAccountMapping cncc = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping("Charge Non Collect Comm");
                            acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                            acrbatchinput_GL_charge.voucher_type = "SH";
                            acrbatchinput_GL_charge.trans_type = "GL";
                            acrbatchinput_GL_charge.client = profitCentre.client;
                            acrbatchinput_GL_charge.apar_type = "";
                            //acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                            //acrbatchinput_GL_charge.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL_charge.account = cncc.cargorelet_account_OUT_SG;// "5101";//Carina19042013 itemChargeType.freighthire_account;
                            acrbatchinput_GL_charge.dim_1 = profitCentre.agr_rel_value; //23092013 profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL_charge.dim_2 = "";
                            acrbatchinput_GL_charge.dim_3 = "";
                            acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                            // acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                            acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL_charge.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL_charge.dim_7 = "";
                            acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                            acrbatchinput_GL_charge.tax_system = "";
                            acrbatchinput_GL_charge.currency = ci.invoice_currency;
                            acrbatchinput_GL_charge.cur_amount = item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.amount = item.charge_amount;//04092013  item.charge_non_collect_comm;
                            acrbatchinput_GL_charge.description = "Charge Non Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL_charge.trans_date = DateTime.Today;// ci.invoice_date;
                            acrbatchinput_GL_charge.voucher_date = ci.invoice_date.Date;
                            acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL_charge.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL_charge.status = "N";
                            acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                            acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL_charge.batch_id = batchID;
                            acrbatchinput_GL_charge.interface_ = "SH";
                            acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL_charge.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL_charge);
                            totalGL += acrbatchinput_GL_charge.amount;

                            acrbatchinput acrbatchinput_GL_charge_reverse = acrbatchinput_GL_charge.Duplicate();
                            acrbatchinput_GL_charge_reverse.cur_amount = -acrbatchinput_GL_charge_reverse.cur_amount;
                            acrbatchinput_GL_charge_reverse.amount = -acrbatchinput_GL_charge_reverse.amount;
                            acrbatchinput_GL_charge_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_charge_reverse.trans_date = NextDateInMonth;
                            acrbatchinput_GL_charge_reverse.batch_id = batchIDReverse;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_charge_reverse);
                        }
                        else
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SH";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            //acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            //acrbatchinput_GL.apar_name = customer.agr_cust_apar_name;
                            acrbatchinput_GL.account = itemChargeType.cargorelet_account_OUT_SG;
                                //item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account; // 03072013
                            acrbatchinput_GL.dim_1 = profitCentre.agr_rel_value; //23092013 
                                //acrbatchinput_GL.account.Trim() == "3334" ?
                                //profitCentreVessel.agr_rel_value : // 05092013
                                //profitCentre.agr_rel_value // 05092013
                                //;//23042013 Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = profitCentreVessel.agr_dim_value + "-V000";//03102013
                            //  acrbatchinput_GL.dim_4 =
                               // acrbatchinput_GL.account.Trim() == "3334" ? "" :
                                //profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013 CArina
                            //if (ci.voyage_no.ToString().Length >= 8)//03072013
                            //{
                             //   acrbatchinput_GL.dim_4 = "";
                           // }
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            acrbatchinput_GL.tax_code = itemChargeType.cargorelet_account_OUT_SG_GST;
                                //item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = item.charge_amount;
                            acrbatchinput_GL.amount = item.charge_amount;
                            acrbatchinput_GL.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = DateTime.Today;// ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SH";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;

                            acrbatchinput acrbatchinput_GL_reverse = acrbatchinput_GL.Duplicate();
                            acrbatchinput_GL_reverse.cur_amount = -acrbatchinput_GL_reverse.cur_amount;
                            acrbatchinput_GL_reverse.amount = -acrbatchinput_GL_reverse.amount;
                            acrbatchinput_GL_reverse.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL_reverse.batch_id = batchIDReverse;
                            acrbatchinput_GL_reverse.trans_date = NextDateInMonth;
                            acrbatchinputListReverse.Add(acrbatchinput_GL_reverse);
                        }
                    }
                    if (acrbatchinput_AP.amount + totalGL != 0)
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                        }
                        continue;
                    }
                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //disable----------production 03092013
                    //foreach (acrbatchinput acr in acrbatchinputListReverse)
                    //{
                    //    m_AcrBatcInputService.Insert(acr);
                    //    m_AcrBatcInputService.InsertToInterfaceTable(acr);
                    //    agrtid += ";" + acr.agrtid.ToString();
                    //}
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }

        }
        public void ExecuteInvoiceProforma()
        {
            // if (DateTime.Today.Day != DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month)) return; //every last date of month;
            try
            {
                IList invoiceNumbers = GetAllProformaPendingLastMOnthPeriod(); //GetAllProformaPendingLastMOnthPeriod(new DateTime(2013, 8, 1)); // 
                //IList invoiceNumbers = GetAllProformaPending();
                IList proformaInvoices = new ArrayList();
                foreach (InvoiceProforma ip in invoiceNumbers)
                {
                    CommissionInvoice ci = null;
                    IList items = GetProformaItem(ip);
                    if (ci == null)
                    {
                        ci = (CommissionInvoice)items[0];
                        ci.Header = (CommissionInvoice)items[0];
                        ci.Items = items;
                    }
                    proformaInvoices.Add(ci);
                }
                DateTime lastDateInMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month));//new DateTime(2013, 8, 31);//
                DateTime NextDateInMonth = lastDateInMonth.AddDays(1);
                int batchNumber = Convert.ToInt32(DateTime.Now.ToString("HHmmss"));

                foreach (CommissionInvoice ci in proformaInvoices)
                {
                    //if(ci.invoice_number != "Bilis12/7")continue;
                    //SupplierCustomer customer = m_suppCusService.GetCustomerMapping(ci.company);
                    ProfitCentre profitCentre = m_profitCentreService.GetProfitCentreMapping(ci.profit_centre);
                    profitCentre.CommissionManager = m_profitCentreService.GetProfitCentreByID(profitCentre.CommissionManager.profit_centre_id);
                    //ResponsibleUser user = m_ResponsibleUserService.GetResponsibleUserByName(ci.raised_to_final_by);
                    m_vesselService.FindVesselByName(ci.vessel_name,ci.vessel_sid, ci.profit_centre); // vessel validation inserting if not found------------
                    // ChargeTypeAccountMapping chargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(ci.charge_type);

                    string alert = "";
                    //if (customer.agr_cust_apar_id == "")
                    //{
                    //    //m_alertService.CheckAndUpdateAlert(ci.commission_invoice_id.ToString(), AlertType.SOFTMAR_FREIGHT_HIRE_INVOICE, AlertStatus.PENDING,
                    //    //  string.Format("Can not find company : {0} in agresso", customer.full_name) + alert, ci.invoice_number);
                    //    //continue;
                    //    alert += string.Format("-[E005] Unable to find apar_ID for Company '{0}' \r\n", customer.full_name);
                    //};
                    if (profitCentre.agr_dim_value == "") { alert += string.Format("-[E004] Unable to find Dim_Val for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    if (profitCentre.client == "") { alert += string.Format("-[E007] Unable to find client for Profit Centre '{0}' \r\n", profitCentre.full_name); }//alert
                    Vessel profitCentreVessel = m_vesselService.GetVesselMappingByProfitCentreIDAndVesselName(profitCentre.profit_centre_id, ci.vessel_name.Trim(), profitCentre.client.Trim());
                    bool validVoyage = ci.voyage_no.ToString().Length >= 8 ? true : m_ud_voyageimp_Service.IsRegisteredVoyage(profitCentreVessel == null ? "" : profitCentreVessel.agr_dim_value, ci.voyage_no);
                    //agldimvalue icVessel = m_agldimvalueService.GetICVesselDimValue(profitCentreVessel == null ? "XXX" : profitCentreVessel.agr_dim_value);
                    //agldimvalue icVoyage = m_agldimvalueService.GetICVoyageDimValue((profitCentreVessel == null ? "XXX" : (profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'))));

                    if (profitCentreVessel == null) { alert += string.Format("-[E015] Unable to find Vessel '{0}' under Profit Centre '{1} ({2})' \r\n", ci.vessel_name.Trim(), profitCentre.full_name, profitCentre.agr_dim_value); }
                    if (profitCentreVessel != null && profitCentreVessel.agr_dim_value == "") { alert += string.Format("-[E010] Unable to find Dim_Val Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    if (profitCentreVessel != null && profitCentreVessel.agr_rel_value == "") { alert += string.Format("-[E008] Unable to find Cost Centre Code for Vessel '{0}' \r\n", profitCentreVessel.vessel_name); }//alert
                    //  if (profitCentreVessel != null && icVessel == null) { alert += string.Format("-Unable to find IC Vessel value Code for Vessel '{0}' \r\n", profitCentreVessel.agr_dim_value); } //alert could not  find vessel dim val
                    //  if (profitCentreVessel != null && icVoyage == null) { alert += string.Format("-Unable to find IC Voyage value Code for Voyage '{0}' \r\n", profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0')); } //alert could not  find vessel dim val
                    if (!validVoyage)
                    {
                        alert += string.Format("-[E016] Unable to Find Voyage in Voyage Master, Vessel: '{0}' Voyage: '{1}' Code:'{2}' \r\n",
                            ci.vessel_name.Trim(), ci.voyage_no, (profitCentreVessel != null ? profitCentreVessel.agr_dim_value : "") + "-V" + ci.voyage_no.ToString().PadLeft(3, '0'));
                    }
                    //if (chargeType.freighthire_account == "") { alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'", chargeType.charge_type); } //alert coudnot map account on charge type :---------

                    foreach (CommissionInvoice item in ci.Items)
                    {
                        ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                        if (itemChargeType.chartererInv_account == "")
                        {
                            alert += string.Format("-[E017] Unable to find Account Map for Charge Type '{0}'  \r\n", itemChargeType.charge_type);
                        }
                    }
                    if (alert != "")
                    {
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            updateRemarks(item.commission_invoice_id, alert, item.remarks, "0");
                        }
                        //  m_alertService.CheckAndUpdateAlert(ci.commission_invoice_id.ToString(), AlertType.SOFTMAR_FREIGHT_HIRE_INVOICE, AlertStatus.PENDING,
                        //     string.Format("Failed while interfacing Invoice No.{0}, Invoice Date :{3}, Company Name : {1}, Description : {2}  \r\n", ci.invoice_number, ci.company, ci.charge_description, ci.invoice_date.ToString("dd-MMM-yyyy")) + alert, ci.invoice_number);
                        continue;
                    }
                    //  else
                    //  {
                    //      m_alertService.CheckAndUpdateAlert(ci.commission_invoice_id.ToString(), AlertType.SOFTMAR_FREIGHT_HIRE_INVOICE, AlertStatus.RESOLVED,
                    //            string.Format("Failed while interfacing Invoice No.{0}, Invoice Date :{3}, Company Name : {1}, Description : {2}  \r\n", ci.invoice_number, ci.company, ci.charge_description, ci.invoice_date.ToString("dd-MMM-yyyy")) + alert, ci.invoice_number);
                    //  }

                    IList acrbatchinputList = new ArrayList();
                    int voucherNumber = GetVoucherRunningNumber();
                    string batchID = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchNumber++.ToString().PadLeft(6, '0');
                    #region DEBIT
                    if (ci.invoice_type == "Charge Credit" || ci.invoice_type == "Charge Debit")
                    {
                        #region Charge Credit & Charge Debit REGION
                        acrbatchinput acrbatchinput_AP = new acrbatchinput();
                        acrbatchinput_AP.voucher_type = "SH";
                        acrbatchinput_AP.trans_type = "GL";
                        acrbatchinput_AP.client = profitCentre.client;
                        acrbatchinput_AP.apar_type = "";
                        // acrbatchinput_AP.apar_id = customer.agr_cust_apar_id;
                        // acrbatchinput_AP.apar_name = customer.agr_supp_apar_name;
                        acrbatchinput_AP.account = "2201";//12072013 "3302";
                        acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                        acrbatchinput_AP.dim_2 = "";
                        acrbatchinput_AP.dim_3 = "";
                        acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        if (ci.voyage_no.ToString().Length >= 8)//03072013
                        {
                            acrbatchinput_AP.dim_4 = "";
                        }
                        acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                        acrbatchinput_AP.dim_6 = profitCentre.CommissionManager.agr_dim_value;// profitCentre.agr_dim_value;
                        acrbatchinput_AP.dim_7 = "";
                        acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                        acrbatchinput_AP.tax_system = "";
                        acrbatchinput_AP.currency = ci.invoice_currency;
                        acrbatchinput_AP.cur_amount = ci.invoice_amount;
                        acrbatchinput_AP.amount = ci.invoice_amount;
                        acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                        acrbatchinput_AP.trans_date = lastDateInMonth;//ci.invoice_date;
                        acrbatchinput_AP.voucher_date = ci.invoice_date.Date;
                        acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                        acrbatchinput_AP.ext_inv_ref = "";//12072013 ci.invoice_number;
                        acrbatchinput_AP.status = "N";
                        acrbatchinput_AP.due_date = ci.invoice_due_date;
                        acrbatchinput_AP.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                        acrbatchinput_AP.batch_id = batchID;
                        acrbatchinput_AP.interface_ = "SH";
                        acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                        acrbatchinput_AP.pay_temp_id = "";//12072013 "IM";//09062013
                        acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                        acrbatchinputList.Add(acrbatchinput_AP);

                        decimal totalGL = 0;
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SH";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            // acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            // acrbatchinput_GL.apar_name = customer.agr_supp_apar_name;
                            acrbatchinput_GL.account = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account; // item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.freighthire_account; // 03072013
                            acrbatchinput_GL.dim_1 = acrbatchinput_GL.account.Trim() == "3334" ? profitCentre.agr_rel_value : profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = acrbatchinput_GL.account.Trim() == "3334" ? "" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013CArina
                            if (ci.voyage_no.ToString().Length >= 8)//03072013
                            {
                                acrbatchinput_GL.dim_4 = "";
                            }
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            acrbatchinput_GL.tax_code = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = -item.charge_amount;
                            acrbatchinput_GL.amount = -item.charge_amount;
                            acrbatchinput_GL.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = lastDateInMonth;//ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = "";// ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SH";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "";//12072013 "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;

                            if (item.charge_addr_comm != 0)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                //  acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                //  acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = item.charge_addr_comm;
                                acrbatchinput_GL_charge.amount = item.charge_addr_comm;
                                acrbatchinput_GL_charge.description = "Charge Address Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = lastDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                            if (ci.invoice_type == "Charge Credit" && item.charge_collect_comm != 0)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                // acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                // acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.amount = item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = lastDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                            if (ci.invoice_type == "Charge Debit" && item.charge_non_collect_comm != 0)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                // acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                // acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.amount = item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.description = "Charge Non Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = lastDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                        }
                        if (acrbatchinput_AP.amount + totalGL != 0)
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                        #endregion
                    }
                    else
                    {
                        #region Commission Credit REGION
                        acrbatchinput acrbatchinput_AP = new acrbatchinput();
                        acrbatchinput_AP.voucher_type = "SH";
                        acrbatchinput_AP.trans_type = "GL";
                        acrbatchinput_AP.client = profitCentre.client;
                        acrbatchinput_AP.apar_type = "";
                        // acrbatchinput_AP.apar_id = customer.agr_cust_apar_id;
                        // acrbatchinput_AP.apar_name = customer.agr_supp_apar_name;
                        acrbatchinput_AP.account = "2201";//12072013 "3302";
                        acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                        acrbatchinput_AP.dim_2 = "";
                        acrbatchinput_AP.dim_3 = "";
                        acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        if (ci.voyage_no.ToString().Length >= 8)//03072013
                        {
                            acrbatchinput_AP.dim_4 = "";
                        }
                        acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                        acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;// profitCentre.agr_dim_value;
                        acrbatchinput_AP.dim_7 = "";
                        acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                        acrbatchinput_AP.tax_system = "";
                        acrbatchinput_AP.currency = ci.invoice_currency;
                        acrbatchinput_AP.cur_amount = ci.invoice_amount;
                        acrbatchinput_AP.amount = ci.invoice_amount;
                        acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                        acrbatchinput_AP.trans_date = lastDateInMonth;//ci.invoice_date;
                        acrbatchinput_AP.voucher_date = ci.invoice_date;
                        acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                        acrbatchinput_AP.ext_inv_ref = "";//12072013 ci.invoice_number;
                        acrbatchinput_AP.status = "N";
                        acrbatchinput_AP.due_date = ci.invoice_due_date;
                        acrbatchinput_AP.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                        acrbatchinput_AP.batch_id = batchID;
                        acrbatchinput_AP.interface_ = "SH";
                        acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                        acrbatchinput_AP.pay_temp_id = "";//12072013 "IM";//09062013
                        acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                        acrbatchinputList.Add(acrbatchinput_AP);

                        decimal totalGL = 0;

                        if (ci.Items.Count == 1)
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(ci.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SH";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            // acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            // acrbatchinput_GL.apar_name = customer.agr_supp_apar_name;
                            acrbatchinput_GL.account = ci.voyage_type.Trim() == "Cargo Relet" && ci.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account; // item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.freighthire_account; // 03072013
                            acrbatchinput_GL.dim_1 = acrbatchinput_GL.account.Trim() == "3334" ? profitCentre.agr_rel_value : profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = acrbatchinput_GL.account.Trim() == "3334" ? "" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013CArina
                            if (ci.voyage_no.ToString().Length >= 8)//03072013
                            {
                                acrbatchinput_GL.dim_4 = "";
                            }
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            acrbatchinput_GL.tax_code = ci.voyage_type.Trim() == "Cargo Relet" && ci.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = -ci.invoice_amount;
                            acrbatchinput_GL.amount = -ci.invoice_amount;
                            acrbatchinput_GL.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = lastDateInMonth;//ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = "";//12072013  ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SH";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "";//12072013 "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;
                        }
                        else
                        {
                            foreach (CommissionInvoice i in ci.Items)
                            {
                                GetCollectCommission(i);
                            }
                            int comm = 0;
                            decimal total = ci.GetTotalCollectCommission();

                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission1();
                                comm = 1;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission2();
                                comm = 2;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission3();
                                comm = 3;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission4();
                                comm = 4;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalChargeAddressCommission();
                                comm = 5;
                            }

                            foreach (CommissionInvoice item in ci.Items)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                // acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                // acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = -item.GetCollectCommissionAmount(comm);
                                acrbatchinput_GL_charge.amount = -item.GetCollectCommissionAmount(comm);
                                acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = lastDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(lastDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                        }
                        if (acrbatchinput_AP.amount + totalGL != 0)
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                        #endregion
                    }
                    #endregion

                    batchID = "SH" + DateTime.Now.ToString("ddMMyyyy") + batchNumber++.ToString().PadLeft(6, '0');
                    #region CREDIT NEXT MONTH

                    if (ci.invoice_type == "Charge Credit" || ci.invoice_type == "Charge Debit")
                    {
                        #region Charge Credit & Charge Debit REGION
                        acrbatchinput acrbatchinput_AP = new acrbatchinput();
                        acrbatchinput_AP.voucher_type = "SH";
                        acrbatchinput_AP.trans_type = "GL";
                        acrbatchinput_AP.client = profitCentre.client;
                        acrbatchinput_AP.apar_type = "";
                        // acrbatchinput_AP.apar_id = customer.agr_cust_apar_id;
                        // acrbatchinput_AP.apar_name = customer.agr_supp_apar_name;
                        acrbatchinput_AP.account = "2201";//12072013 "3302";
                        acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                        acrbatchinput_AP.dim_2 = "";
                        acrbatchinput_AP.dim_3 = "";
                        acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        if (ci.voyage_no.ToString().Length >= 8)//03072013
                        {
                            acrbatchinput_AP.dim_4 = "";
                        }
                        acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                        acrbatchinput_AP.dim_6 = profitCentre.CommissionManager.agr_dim_value;// profitCentre.agr_dim_value;
                        acrbatchinput_AP.dim_7 = "";
                        acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                        acrbatchinput_AP.tax_system = "";
                        acrbatchinput_AP.currency = ci.invoice_currency;
                        acrbatchinput_AP.cur_amount = -ci.invoice_amount;
                        acrbatchinput_AP.amount = -ci.invoice_amount;
                        acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                        acrbatchinput_AP.trans_date = NextDateInMonth;//ci.invoice_date;
                        acrbatchinput_AP.voucher_date = ci.invoice_date;
                        acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                        acrbatchinput_AP.ext_inv_ref = "";//12072013 ci.invoice_number;
                        acrbatchinput_AP.status = "N";
                        acrbatchinput_AP.due_date = ci.invoice_due_date;
                        acrbatchinput_AP.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                        acrbatchinput_AP.batch_id = batchID;
                        acrbatchinput_AP.interface_ = "SH";
                        acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                        acrbatchinput_AP.pay_temp_id = "";//12072013 "IM";//09062013
                        acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                        acrbatchinputList.Add(acrbatchinput_AP);

                        decimal totalGL = 0;
                        foreach (CommissionInvoice item in ci.Items)
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(item.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SH";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            // acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            // acrbatchinput_GL.apar_name = customer.agr_supp_apar_name;
                            acrbatchinput_GL.account = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account; // item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.freighthire_account; // 03072013
                            acrbatchinput_GL.dim_1 = acrbatchinput_GL.account.Trim() == "3334" ? profitCentre.agr_rel_value : profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = acrbatchinput_GL.account.Trim() == "3334" ? "" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013CArina
                            if (ci.voyage_no.ToString().Length >= 8)//03072013
                            {
                                acrbatchinput_GL.dim_4 = "";
                            }
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            acrbatchinput_GL.tax_code = item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = item.charge_amount;
                            acrbatchinput_GL.amount = item.charge_amount;
                            acrbatchinput_GL.description = item.charge_type + ":" + item.charge_description + "-" + item.invoice_number + "-" + item.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = NextDateInMonth;//ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = "";// ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SH";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "";//12072013 "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;

                            if (item.charge_addr_comm != 0)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                //  acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                //  acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = -item.charge_addr_comm;
                                acrbatchinput_GL_charge.amount = -item.charge_addr_comm;
                                acrbatchinput_GL_charge.description = "Charge Address Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = NextDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                            if (ci.invoice_type == "Charge Credit" && item.charge_collect_comm != 0)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                // acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                // acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = -item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.amount = -item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = NextDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                            if (ci.invoice_type == "Charge Debit" && item.charge_non_collect_comm != 0)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                // acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                // acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = -item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.amount = -item.charge_non_collect_comm;
                                acrbatchinput_GL_charge.description = "Charge Non Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = NextDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                        }
                        if (acrbatchinput_AP.amount + totalGL != 0)
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                        #endregion
                    }
                    else
                    {
                        #region Commission Credit REGION
                        acrbatchinput acrbatchinput_AP = new acrbatchinput();
                        acrbatchinput_AP.voucher_type = "SH";
                        acrbatchinput_AP.trans_type = "GL";
                        acrbatchinput_AP.client = profitCentre.client;
                        acrbatchinput_AP.apar_type = "";
                        // acrbatchinput_AP.apar_id = customer.agr_cust_apar_id;
                        // acrbatchinput_AP.apar_name = customer.agr_supp_apar_name;
                        acrbatchinput_AP.account = "2201";//12072013 "3302";
                        acrbatchinput_AP.dim_1 = profitCentre.agr_rel_value;
                        acrbatchinput_AP.dim_2 = "";
                        acrbatchinput_AP.dim_3 = "";
                        acrbatchinput_AP.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                        if (ci.voyage_no.ToString().Length >= 8)//03072013
                        {
                            acrbatchinput_AP.dim_4 = "";
                        }
                        acrbatchinput_AP.dim_5 = profitCentreVessel.agr_dim_value;
                        acrbatchinput_AP.dim_6 = profitCentre.agr_dim_value;// profitCentre.agr_dim_value;
                        acrbatchinput_AP.dim_7 = "";
                        acrbatchinput_AP.tax_code = "";// 09 Apr 2013 Carina "0";
                        acrbatchinput_AP.tax_system = "";
                        acrbatchinput_AP.currency = ci.invoice_currency;
                        acrbatchinput_AP.cur_amount = -ci.invoice_amount;
                        acrbatchinput_AP.amount = -ci.invoice_amount;
                        acrbatchinput_AP.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                        acrbatchinput_AP.trans_date = NextDateInMonth;//ci.invoice_date;
                        acrbatchinput_AP.voucher_date = ci.invoice_date;
                        acrbatchinput_AP.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                        acrbatchinput_AP.ext_inv_ref = "";//12072013 ci.invoice_number;
                        acrbatchinput_AP.status = "N";
                        acrbatchinput_AP.due_date = ci.invoice_due_date;
                        acrbatchinput_AP.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                        acrbatchinput_AP.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                        acrbatchinput_AP.batch_id = batchID;
                        acrbatchinput_AP.interface_ = "SH";
                        acrbatchinput_AP.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                        acrbatchinput_AP.pay_temp_id = "";//12072013 "IM";//09062013
                        acrbatchinput_AP.sequence_no = GetSequenceRunningNumber();
                        acrbatchinputList.Add(acrbatchinput_AP);

                        decimal totalGL = 0;

                        if (ci.Items.Count == 1)
                        {
                            ChargeTypeAccountMapping itemChargeType = m_ChargeTypeAccountMappingService.GetChargeTypeAccountMapping(ci.charge_type);
                            acrbatchinput acrbatchinput_GL = new acrbatchinput();
                            acrbatchinput_GL.voucher_type = "SH";
                            acrbatchinput_GL.trans_type = "GL";
                            acrbatchinput_GL.client = profitCentre.client;
                            acrbatchinput_GL.apar_type = "";
                            // acrbatchinput_GL.apar_id = customer.agr_cust_apar_id;
                            // acrbatchinput_GL.apar_name = customer.agr_supp_apar_name;
                            acrbatchinput_GL.account = ci.voyage_type.Trim() == "Cargo Relet" && ci.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.chartererInv_account; // item.voyage_type.Trim() == "Cargo Relet" && item.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN : itemChargeType.freighthire_account; // 03072013
                            acrbatchinput_GL.dim_1 = acrbatchinput_GL.account.Trim() == "3334" ? profitCentre.agr_rel_value : profitCentreVessel.agr_rel_value;//23042013Carina
                            acrbatchinput_GL.dim_2 = "";
                            acrbatchinput_GL.dim_3 = "";
                            acrbatchinput_GL.dim_4 = acrbatchinput_GL.account.Trim() == "3334" ? "" : profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0'); //23042013CArina
                            if (ci.voyage_no.ToString().Length >= 8)//03072013
                            {
                                acrbatchinput_GL.dim_4 = "";
                            }
                            acrbatchinput_GL.dim_5 = profitCentreVessel.agr_dim_value;
                            acrbatchinput_GL.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                            acrbatchinput_GL.dim_7 = "";
                            acrbatchinput_GL.tax_code = ci.voyage_type.Trim() == "Cargo Relet" && ci.voyage_no.ToString().Length >= 8 ? itemChargeType.cargorelet_account_IN_GST : itemChargeType.chartererInv_tax_account;// "";// 09 Apr 2013 Carina"0"
                            acrbatchinput_GL.tax_system = "";
                            acrbatchinput_GL.currency = ci.invoice_currency;
                            acrbatchinput_GL.cur_amount = ci.invoice_amount;
                            acrbatchinput_GL.amount = ci.invoice_amount;
                            acrbatchinput_GL.description = ci.charge_type + ":" + ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                            acrbatchinput_GL.description = acrbatchinput_GL.description.Length > 255 ? acrbatchinput_GL.description.Substring(0, 255) : acrbatchinput_GL.description;
                            acrbatchinput_GL.trans_date = NextDateInMonth;//ci.invoice_date;
                            acrbatchinput_GL.voucher_date = ci.invoice_date;
                            acrbatchinput_GL.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                            acrbatchinput_GL.ext_inv_ref = "";//12072013  ci.invoice_number;
                            acrbatchinput_GL.status = "N";
                            acrbatchinput_GL.due_date = ci.invoice_due_date;
                            acrbatchinput_GL.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                            acrbatchinput_GL.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                            acrbatchinput_GL.batch_id = batchID;
                            acrbatchinput_GL.interface_ = "SH";
                            acrbatchinput_GL.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                            acrbatchinput_GL.pay_temp_id = "";//12072013 "IM";//09062013
                            acrbatchinput_GL.sequence_no = GetSequenceRunningNumber();
                            acrbatchinputList.Add(acrbatchinput_GL);
                            totalGL += acrbatchinput_GL.amount;
                        }
                        else
                        {
                            foreach (CommissionInvoice i in ci.Items)
                            {
                                GetCollectCommission(i);
                            }
                            int comm = 0;
                            decimal total = ci.GetTotalCollectCommission();

                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission1();
                                comm = 1;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission2();
                                comm = 2;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission3();
                                comm = 3;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalCollectCommission4();
                                comm = 4;
                            }
                            if (total != ci.invoice_amount)
                            {
                                total = ci.GetTotalChargeAddressCommission();
                                comm = 5;
                            }

                            foreach (CommissionInvoice item in ci.Items)
                            {
                                acrbatchinput acrbatchinput_GL_charge = new acrbatchinput();
                                acrbatchinput_GL_charge.voucher_type = "SH";
                                acrbatchinput_GL_charge.trans_type = "GL";
                                acrbatchinput_GL_charge.client = profitCentre.client;
                                acrbatchinput_GL_charge.apar_type = "";
                                // acrbatchinput_GL_charge.apar_id = customer.agr_cust_apar_id;
                                // acrbatchinput_GL_charge.apar_name = customer.agr_supp_apar_name;
                                acrbatchinput_GL_charge.account = "5101";//Carina19042013 itemChargeType.freighthire_account;
                                acrbatchinput_GL_charge.dim_1 = profitCentreVessel.agr_rel_value;//23042013Carina
                                acrbatchinput_GL_charge.dim_2 = "";
                                acrbatchinput_GL_charge.dim_3 = "";
                                acrbatchinput_GL_charge.dim_4 = profitCentreVessel.agr_dim_value + "-V" + ci.voyage_no.PadLeft(3, '0');
                                acrbatchinput_GL_charge.dim_5 = profitCentreVessel.agr_dim_value;
                                acrbatchinput_GL_charge.dim_6 = profitCentre.CommissionManager.agr_dim_value;//profitCentre.agr_dim_value;
                                acrbatchinput_GL_charge.dim_7 = "";
                                acrbatchinput_GL_charge.tax_code = "ZO";//carina19042013 itemChargeType.freighthire_tax_account;//"";// 09 Apr 2013 Carina"0";
                                acrbatchinput_GL_charge.tax_system = "";
                                acrbatchinput_GL_charge.currency = ci.invoice_currency;
                                acrbatchinput_GL_charge.cur_amount = item.GetCollectCommissionAmount(comm);
                                acrbatchinput_GL_charge.amount = item.GetCollectCommissionAmount(comm);
                                acrbatchinput_GL_charge.description = "Charge Collect Comm";//carina19042013 ci.charge_description + "-" + ci.invoice_number + "-" + ci.raised_to_final_by;
                                acrbatchinput_GL_charge.trans_date = NextDateInMonth;//ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_date = ci.invoice_date;
                                acrbatchinput_GL_charge.voucher_no = voucherNumber;//1; 09 Apr 2013 - Carina1;1;
                                acrbatchinput_GL_charge.ext_inv_ref = "";//12072013 ci.invoice_number;
                                acrbatchinput_GL_charge.status = "N";
                                acrbatchinput_GL_charge.due_date = ci.invoice_due_date;
                                acrbatchinput_GL_charge.period = Convert.ToInt32(NextDateInMonth.ToString("yyyyMM"));
                                acrbatchinput_GL_charge.responsible = "DEV01";//16072013 user.agresso_user; //"DEV01";
                                acrbatchinput_GL_charge.batch_id = batchID;
                                acrbatchinput_GL_charge.interface_ = "SH";
                                acrbatchinput_GL_charge.disc_date = DateTime.Now;//07062013 ci.invoice_date; //carina19042013
                                acrbatchinput_GL_charge.pay_temp_id = "";//12072013 "IM";//09062013
                                acrbatchinput_GL_charge.sequence_no = GetSequenceRunningNumber();
                                acrbatchinputList.Add(acrbatchinput_GL_charge);
                                totalGL += acrbatchinput_GL_charge.amount;
                            }
                        }
                        if (acrbatchinput_AP.amount + totalGL != 0)
                        {
                            foreach (CommissionInvoice item in ci.Items)
                            {
                                updateRemarks(item.commission_invoice_id, "-[E002] AP and GL is not balance, please contact administrator", item.remarks, "2");
                            }
                            continue;
                        }
                        #endregion
                    }
                    #endregion

                    string agrtid = "";
                    foreach (acrbatchinput acr in acrbatchinputList)
                    {
                        m_AcrBatcInputService.Insert(acr);
                        m_AcrBatcInputService.InsertToInterfaceTable(acr);
                        agrtid += ";" + acr.agrtid.ToString();
                    }
                    //update status-------
                    foreach (CommissionInvoice item in ci.Items)
                    {
                        agrtid = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        SqlCommand cmd = new SqlCommand();
                        m_dataBaseConectivity.InterfaceSqlConnection.Open();
                        cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                        cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTempPickup_flagStatus();
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "1";
                        cmd.Parameters.Add("@pickup_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@pickup_update_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@agrtidList", SqlDbType.NVarChar).Value = agrtid.Length > 250 ? agrtid.Substring(0, 250) : agrtid;
                        cmd.Parameters.Add("@remarks", SqlDbType.NVarChar).Value = "";
                        cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = item.commission_invoice_id;
                        cmd.Parameters.Add("@batch_id", SqlDbType.NVarChar).Value = batchID;
                        cmd.ExecuteNonQuery();
                        m_dataBaseConectivity.InterfaceSqlConnection.Close();
                    }
                }
            }
            catch (Exception x)
            {
                LogService.WriteLogException(x);
                throw x;
            }
            finally
            {

            }
        }
        private int GetVoucherRunningNumber()
        {
            ConfigurationSetting runningNumber = m_configSettingService.GetConfigurationSetting("RunningNumber");
            int number = Convert.ToInt32(runningNumber.val_1) + 1;
            runningNumber.val_1 = number.ToString();
            m_configSettingService.UpdateConfiguration(runningNumber);
            return number;
        }
        private int GetSequenceRunningNumber()
        {
            ConfigurationSetting runningNumber = m_configSettingService.GetConfigurationSetting("RunningNumber");
            int number = Convert.ToInt32(runningNumber.val_2) + 1;
            runningNumber.val_2 = number.ToString();
            m_configSettingService.UpdateConfiguration(runningNumber);
            return number;
        }
        private bool validateProfitCentre(CommissionInvoice ci, agldimvalue agrProfitCentre, AlertType alertType)
        {
            bool valid = agrProfitCentre != null;
            Alert alert = m_alertService.FindAlertByKey(ci.invoice_number.Trim() + ci.profit_centre.Trim(), alertType);
            if (valid)
            {
                if (alert != null)
                {
                    alert.alert_status = AlertStatus.RESOLVED;
                    m_alertService.UpdateAlertStatus(alert);
                }
            }
            else
            {
                if (alert == null)
                    m_alertService.InsertAlert(new Alert(alertType, string.Format("Unable to find Profit Centre with name ' {0} ' in agldimvalue - Agresso for Invoice# {1} ",
                        ci.profit_centre.Trim(), ci.invoice_number.Trim()), AlertStatus.PENDING, ci.invoice_number.Trim() + ci.profit_centre.Trim(), "Profit Centre"));
                else
                    m_alertService.UpdateAlertStatus(alert);
            }
            return valid;
        }
        private bool validateSupplier(CommissionInvoice ci, asuheader agrSupplier, AlertType alertType)
        {
            bool valid = agrSupplier != null;
            Alert alert = m_alertService.FindAlertByKey(ci.invoice_number.Trim() + ci.company.Trim(), alertType);
            if (valid)
            {
                if (alert != null)
                {
                    alert.alert_status = AlertStatus.RESOLVED;
                    m_alertService.UpdateAlertStatus(alert);
                }
            }
            else
            {
                if (alert == null)
                    m_alertService.InsertAlert(new Alert(alertType, string.Format("Unable to find Supplier with name ' {0} ' in asuheader - Agresso for Invoice# {1}",
                        ci.company.Trim(), ci.invoice_number.Trim()), AlertStatus.PENDING, ci.invoice_number.Trim() + ci.company.Trim(), "Supplier"));
                else
                    m_alertService.UpdateAlertStatus(alert);
            }
            return valid;
        }
        private bool validateVessel(CommissionInvoice ci, agldimvalue agrVessel, AlertType alertType)
        {
            bool valid = agrVessel != null;
            Alert alert = m_alertService.FindAlertByKey(ci.invoice_number.Trim() + ci.vessel_name.Trim(), alertType);
            if (valid)
            {
                if (alert != null)
                {
                    alert.alert_status = AlertStatus.RESOLVED;
                    m_alertService.UpdateAlertStatus(alert);
                }
            }
            else
            {
                if (alert == null)
                    m_alertService.InsertAlert(new Alert(alertType, string.Format("Unable to find Vessel with name ' {0} ' in agldimvalue - Agresso for Invoice# {1}",
                        ci.vessel_name.Trim(), ci.invoice_number.Trim()), AlertStatus.PENDING, ci.invoice_number.Trim() + ci.vessel_name.Trim(), "Vessel"));
                else
                    m_alertService.UpdateAlertStatus(alert);
            }
            return valid;
        }
        private bool validateCustomer(CommissionInvoice ci, acuheader agrCustomer, AlertType alertType)
        {
            bool valid = agrCustomer != null;
            Alert alert = m_alertService.FindAlertByKey(ci.invoice_number.Trim() + ci.company.Trim(), alertType);
            if (valid)
            {
                if (alert != null)
                {
                    alert.alert_status = AlertStatus.RESOLVED;
                    m_alertService.UpdateAlertStatus(alert);
                }
            }
            else
            {
                if (alert == null)
                    m_alertService.InsertAlert(new Alert(alertType, string.Format("Unable to find Customer with name ' {0} ' in acuheader - Agresso for Invoice# {1}"
                        , ci.company.Trim(), ci.invoice_number.Trim()), AlertStatus.PENDING, ci.invoice_number.Trim() + ci.company.Trim(), "Customer"));
                else
                    m_alertService.UpdateAlertStatus(alert);
            }
            return valid;
        }
        public void ImportAllDataSoftmarToMiddleLayer(SoftmarType type)
        {
            try
            {
                IList commissionInvoices = new ArrayList();
                m_dataBaseConectivity.SoftmarSqlConnection.Open();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.SoftmarSqlConnection;
                SqlDataReader rd;
                if (type == SoftmarType.SOFTMAR_COMMISSION_INVOICE_TCRELET)
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByTCReletTypeAndInvoiceTypeCommission();
                    cmd.CommandTimeout = 300;
                    rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        commissionInvoices.Add(new CommissionInvoice(rd, false));
                    }
                    rd.Close();

                    //cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByVCReletTypeAndInvoiceTypeCommission();
                    //cmd.CommandTimeout = 300;
                    //rd = cmd.ExecuteReader();
                    //while (rd.Read())
                    //{
                    //    commissionInvoices.Add(new CommissionInvoice(rd, false));
                    //}
                    //rd.Close();
                }
                else if (type == SoftmarType.SOFTMAR_FREIGHT_HIRE_INVOICE)
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetFreightHireInvoiceChargeCredit();
                    cmd.CommandTimeout = 300;
                    rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        commissionInvoices.Add(new CommissionInvoice(rd, false));
                    }
                    rd.Close();
                    cmd.CommandText = CommisionInvoiceSQL.GetFreightHireInvoiceChargeDebit();
                    cmd.CommandTimeout = 300;
                    rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        commissionInvoices.Add(new CommissionInvoice(rd, false));
                    }
                    rd.Close();
                }
                //else if (type == SoftmarType.SOFTMAR_PROFORMA)
                //{
                //    cmd.CommandText = CommisionInvoiceSQL.GetProforma();
                //    cmd.CommandTimeout = 300;
                //    rd = cmd.ExecuteReader();
                //    while (rd.Read())
                //    {
                //        commissionInvoices.Add(new CommissionInvoice(rd, false));
                //    }
                //    rd.Close();
                //}

                IList invoiceList = new ArrayList();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetComissionInvoiceMiddleLayer();
                cmd.CommandTimeout = 300;
                cmd.Parameters.Clear();
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    invoiceList.Add(rd[0]);
                }
                rd.Close();

                foreach (CommissionInvoice ci in commissionInvoices)
                {
                //    cmd.CommandText = CommisionInvoiceSQL.CountCommissionInvoiceTemp();
                //    cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                //    cmd.Parameters.Clear();
                //    int found = Convert.ToInt16(cmd.ExecuteScalar());
                    cmd.Parameters.Clear();
                    if (!invoiceList.Contains(ci.invoice_number))
                    {
                        cmd.Parameters.Add("@invoice_number", SqlDbType.NVarChar).Value = ci.invoice_number.Trim();   
                        cmd.Parameters.Add("@charge_description", SqlDbType.NVarChar).Value = ci.charge_description.Trim();
                        cmd.Parameters.Add("@charge_type", SqlDbType.NVarChar).Value = ci.charge_type.Trim();
                        cmd.Parameters.Add("@charge_amount", SqlDbType.Decimal).Value = ci.charge_amount;
                        cmd.Parameters.Add("@charge_addr_comm", SqlDbType.Decimal).Value = ci.charge_addr_comm;
                        cmd.Parameters.Add("@charge_collect_comm", SqlDbType.Decimal).Value = ci.charge_collect_comm;
                        cmd.Parameters.Add("@charge_non_collect_comm", SqlDbType.Decimal).Value = ci.charge_non_collect_comm;
                        //cmd.Parameters.Add("@paid", SqlDbType.NVarChar).Value = ci.paid;
                        //cmd.Parameters.Add("@paid_date", SqlDbType.NVarChar).Value = ci.paid_date;
                        //cmd.Parameters.Add("@charge_addr_comm", SqlDbType.NVarChar).Value = ci.charge_addr_comm;
                        //cmd.Parameters.Add("@charge_collect_comm", SqlDbType.NVarChar).Value = ci.charge_collect_comm;
                        //cmd.Parameters.Add("@charge_non_collect_comm", SqlDbType.NVarChar).Value = ci.charge_non_collect_comm;
                        //cmd.Parameters.Add("@voyage_type", SqlDbType.NVarChar).Value = ci.voyage_type;
                        cmd.Parameters.Add("@invoice_type", SqlDbType.NVarChar).Value = ci.invoice_type.Trim();
                        cmd.Parameters.Add("@company", SqlDbType.NVarChar).Value = ci.company.Trim();
                        cmd.Parameters.Add("@vessel_name", SqlDbType.NVarChar).Value = ci.vessel_name.Trim();
                        cmd.Parameters.Add("@vessel_code", SqlDbType.NVarChar).Value = ci.vessel_sid.Trim();
                        cmd.Parameters.Add("@voyage_no", SqlDbType.NVarChar).Value = ci.voyage_no.Trim();
                        cmd.Parameters.Add("@profit_centre", SqlDbType.NVarChar).Value = ci.profit_centre.Trim();
                        cmd.Parameters.Add("@invoice_date", SqlDbType.DateTime).Value = ci.invoice_date;
                        
                        cmd.Parameters.Add("@invoice_amount", SqlDbType.Decimal).Value = ci.invoice_amount;
                        cmd.Parameters.Add("@invoice_currency", SqlDbType.NVarChar).Value = ci.invoice_currency.Trim();
                        cmd.Parameters.Add("@invoice_due_date", SqlDbType.DateTime).Value = ci.invoice_due_date;

                        cmd.Parameters.Add("@raised_to_final_by", SqlDbType.NVarChar).Value = ci.raised_to_final_by.Trim();
                        
                        //cmd.Parameters.Add("@paid", SqlDbType.Int).Value = ci.paid;
                        //cmd.Parameters.Add("@paid_date", SqlDbType.DateTime).Value = new DateTime(ci.paid_date.Year, ci.paid_date.Month, ci.paid_date.Day);
                       
                        cmd.Parameters.Add("@voyage_type", SqlDbType.NVarChar).Value = ci.voyage_type;
                        cmd.Parameters.Add("@collect_comm", SqlDbType.Decimal).Value = ci.collect_comm;
                        cmd.Parameters.Add("@collect_comm2", SqlDbType.Decimal).Value = ci.collect_comm2;
                        cmd.Parameters.Add("@collect_comm3", SqlDbType.Decimal).Value = ci.collect_comm3;
                        cmd.Parameters.Add("@collect_comm4", SqlDbType.Decimal).Value = ci.collect_comm4;

                        cmd.Parameters.Add("@paid", SqlDbType.Int).Value = ci.paid;
                        cmd.Parameters.Add("@display_order", SqlDbType.Int).Value = ci.display_order;
                        cmd.Parameters.Add("@charge_id", SqlDbType.BigInt).Value = ci.charge_id;
                        cmd.Parameters.Add("@narrative_line", SqlDbType.Int).Value = ci.narrative_line;
                        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ci.ID;

                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "0";
                        cmd.Parameters.Add("@insert_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@narrative", SqlDbType.NVarChar).Value = ci.narrative;


                        cmd.CommandText = CommisionInvoiceSQL.InsertCommissionInvoiceTemp();
                        cmd.ExecuteNonQuery();
                    }
                    //updating display order
                    //else
                    //{
                    //    cmd.CommandText = CommisionInvoiceSQL.CommissionInvoiceTemp();
                    //    ci.commission_invoice_id = Convert.ToInt32(cmd.ExecuteScalar());
                    //    cmd.Parameters.Clear();
                    //    cmd.Parameters.Add("@display_order", SqlDbType.Int).Value = ci.display_order;
                    //    cmd.Parameters.Add("@charge_id", SqlDbType.BigInt).Value = ci.charge_id;
                    //    cmd.Parameters.Add("@narrative_line", SqlDbType.Int).Value = ci.narrative_line;
                    //    cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = ci.commission_invoice_id;
                    //    cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTemp();
                    //    cmd.ExecuteNonQuery();
                    //}
                }
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.SoftmarSqlConnection.Close();
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public void ImportAllDataSoftmarToMiddleLayer(SoftmarType type, string invoiceNumber, bool chargeDebit)
        {
            try
            {
                IList commissionInvoices = new ArrayList();
                m_dataBaseConectivity.SoftmarSqlConnection.Open();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.SoftmarSqlConnection;
                SqlDataReader rd;
                string sql = "";
                if (type == SoftmarType.SOFTMAR_COMMISSION_INVOICE_TCRELET)
                    sql = " and OPINVOICELINENARRATIVE.NarrativeLine in(80) and vInvoiceSrch.Type in ('Commission Credit', 'Commission Debit') ";
                if (type == SoftmarType.SOFTMAR_FREIGHT_HIRE_INVOICE)
                {
                    if(chargeDebit)
                        sql = " and vInvoiceSrch.Type in ('Charge Debit') and VOPINVOICELINENARRATIVE.NarrativeLine not in(80) ";
                    else
                        sql = " and vInvoiceSrch.Type in ('Charge Credit') ";                        
                }
                cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByInvoiceNo(sql);
                cmd.Parameters.Add("@InvoiceNo", SqlDbType.NVarChar).Value = invoiceNumber;
                cmd.CommandTimeout = 300;
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, false));
                }
                rd.Close();
                IList invoiceList = new ArrayList();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetComissionInvoiceMiddleLayer();
                cmd.CommandTimeout = 300;
                cmd.Parameters.Clear();
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    invoiceList.Add(rd[0]);
                }
                rd.Close();
                foreach (CommissionInvoice ci in commissionInvoices)
                {
                    cmd.Parameters.Clear();
                    if (!invoiceList.Contains(ci.invoice_number))
                    {
                        cmd.Parameters.Add("@invoice_number", SqlDbType.NVarChar).Value = ci.invoice_number.Trim();
                        cmd.Parameters.Add("@charge_description", SqlDbType.NVarChar).Value = ci.charge_description.Trim();
                        cmd.Parameters.Add("@charge_type", SqlDbType.NVarChar).Value = ci.charge_type.Trim();
                        cmd.Parameters.Add("@charge_amount", SqlDbType.Decimal).Value = ci.charge_amount;
                        cmd.Parameters.Add("@charge_addr_comm", SqlDbType.Decimal).Value = ci.charge_addr_comm;
                        cmd.Parameters.Add("@charge_collect_comm", SqlDbType.Decimal).Value = ci.charge_collect_comm;
                        cmd.Parameters.Add("@charge_non_collect_comm", SqlDbType.Decimal).Value = ci.charge_non_collect_comm;
                        cmd.Parameters.Add("@invoice_type", SqlDbType.NVarChar).Value = ci.invoice_type.Trim();
                        cmd.Parameters.Add("@company", SqlDbType.NVarChar).Value = ci.company.Trim();
                        cmd.Parameters.Add("@vessel_name", SqlDbType.NVarChar).Value = ci.vessel_name.Trim();
                        cmd.Parameters.Add("@vessel_code", SqlDbType.NVarChar).Value = ci.vessel_sid.Trim();
                        cmd.Parameters.Add("@voyage_no", SqlDbType.NVarChar).Value = ci.voyage_no.Trim();
                        cmd.Parameters.Add("@profit_centre", SqlDbType.NVarChar).Value = ci.profit_centre.Trim();
                        cmd.Parameters.Add("@invoice_date", SqlDbType.DateTime).Value = ci.invoice_date;
                        cmd.Parameters.Add("@invoice_amount", SqlDbType.Decimal).Value = ci.invoice_amount;
                        cmd.Parameters.Add("@invoice_currency", SqlDbType.NVarChar).Value = ci.invoice_currency.Trim();
                        cmd.Parameters.Add("@invoice_due_date", SqlDbType.DateTime).Value = ci.invoice_due_date;
                        cmd.Parameters.Add("@raised_to_final_by", SqlDbType.NVarChar).Value = ci.raised_to_final_by.Trim();
                        cmd.Parameters.Add("@voyage_type", SqlDbType.NVarChar).Value = ci.voyage_type;
                        cmd.Parameters.Add("@collect_comm", SqlDbType.Decimal).Value = ci.collect_comm;
                        cmd.Parameters.Add("@collect_comm2", SqlDbType.Decimal).Value = ci.collect_comm2;
                        cmd.Parameters.Add("@collect_comm3", SqlDbType.Decimal).Value = ci.collect_comm3;
                        cmd.Parameters.Add("@collect_comm4", SqlDbType.Decimal).Value = ci.collect_comm4;
                        cmd.Parameters.Add("@paid", SqlDbType.Int).Value = ci.paid;
                        cmd.Parameters.Add("@display_order", SqlDbType.Int).Value = ci.display_order;
                        cmd.Parameters.Add("@charge_id", SqlDbType.BigInt).Value = ci.charge_id;
                        cmd.Parameters.Add("@narrative_line", SqlDbType.Int).Value = ci.narrative_line;
                        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ci.ID;
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "0";
                        cmd.Parameters.Add("@insert_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@narrative", SqlDbType.NVarChar).Value = ci.narrative;
                        cmd.CommandText = CommisionInvoiceSQL.InsertCommissionInvoiceTemp();
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.SoftmarSqlConnection.Close();
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public void ClearAllProformaTransaction()
        {
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.DeleteAllProforma();
                cmd.ExecuteNonQuery();
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public void ImportAllDataSoftmarToMiddleLayerProforma()
        {
            try
            {
                IList commissionInvoices = new ArrayList();
                m_dataBaseConectivity.SoftmarSqlConnection.Open();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.SoftmarSqlConnection;
                SqlDataReader rd;

                cmd.CommandText = CommisionInvoiceSQL.GetProformaCommissionCredit();
                cmd.CommandTimeout = 300;
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, false));
                }
                rd.Close();

                cmd.CommandText = CommisionInvoiceSQL.GetProformaChargeCredit();
                cmd.CommandTimeout = 300;
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, false));
                }
                rd.Close();
                cmd.CommandText = CommisionInvoiceSQL.GetProformaChargeDebit();
                cmd.CommandTimeout = 300;
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, false));
                }
                rd.Close();

                IList currentInvoices = new ArrayList();
                cmd.CommandText = CommisionInvoiceSQL.GetAllDistinctProformaInvoice();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandTimeout = 300;
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    currentInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();

                foreach (CommissionInvoice ci in commissionInvoices)
                {
                    InvoiceProforma pfr = new InvoiceProforma(ci);
                    if(!currentInvoices.Contains(pfr))
                    {
                        cmd.CommandText = CommisionInvoiceSQL.InsertCommissionInvoiceTemp();
                        cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@company", SqlDbType.NVarChar).Value = ci.company.Trim();
                        cmd.Parameters.Add("@vessel_name", SqlDbType.NVarChar).Value = ci.vessel_name.Trim();
                        cmd.Parameters.Add("@voyage_no", SqlDbType.NVarChar).Value = ci.voyage_no.Trim();
                        cmd.Parameters.Add("@invoice_date", SqlDbType.DateTime).Value = ci.invoice_date;
                        cmd.Parameters.Add("@invoice_amount", SqlDbType.Decimal).Value = ci.invoice_amount;
                        cmd.Parameters.Add("@charge_type", SqlDbType.NVarChar).Value = ci.charge_type.Trim();
                        cmd.Parameters.Add("@invoice_number", SqlDbType.NVarChar).Value = ci.invoice_number.Trim();
                        cmd.Parameters.Add("@invoice_type", SqlDbType.NVarChar).Value = ci.invoice_type.Trim();
                        cmd.Parameters.Add("@vessel_code", SqlDbType.NVarChar).Value = ci.vessel_sid.Trim();
                        cmd.Parameters.Add("@profit_centre", SqlDbType.NVarChar).Value = ci.profit_centre.Trim();
                        cmd.Parameters.Add("@charge_description", SqlDbType.NVarChar).Value = ci.charge_description.Trim();
                        cmd.Parameters.Add("@invoice_currency", SqlDbType.NVarChar).Value = ci.invoice_currency.Trim();
                        cmd.Parameters.Add("@invoice_due_date", SqlDbType.DateTime).Value = ci.invoice_due_date;
                        cmd.Parameters.Add("@raised_to_final_by", SqlDbType.NVarChar).Value = ci.raised_to_final_by.Trim();
                        cmd.Parameters.Add("@charge_amount", SqlDbType.Decimal).Value = ci.charge_amount;
                        //cmd.Parameters.Add("@paid", SqlDbType.Int).Value = ci.paid;
                        //cmd.Parameters.Add("@paid_date", SqlDbType.DateTime).Value = new DateTime(ci.paid_date.Year, ci.paid_date.Month, ci.paid_date.Day);
                        cmd.Parameters.Add("@charge_addr_comm", SqlDbType.Decimal).Value = ci.charge_addr_comm;
                        cmd.Parameters.Add("@charge_collect_comm", SqlDbType.Decimal).Value = ci.charge_collect_comm;
                        cmd.Parameters.Add("@charge_non_collect_comm", SqlDbType.Decimal).Value = ci.charge_non_collect_comm;
                        cmd.Parameters.Add("@voyage_type", SqlDbType.NVarChar).Value = ci.voyage_type;
                        cmd.Parameters.Add("@collect_comm", SqlDbType.Decimal).Value = ci.collect_comm;
                        cmd.Parameters.Add("@collect_comm2", SqlDbType.Decimal).Value = ci.collect_comm2;
                        cmd.Parameters.Add("@collect_comm3", SqlDbType.Decimal).Value = ci.collect_comm3;
                        cmd.Parameters.Add("@collect_comm4", SqlDbType.Decimal).Value = ci.collect_comm4;
                        cmd.Parameters.Add("@paid", SqlDbType.Int).Value = ci.paid;
                        cmd.Parameters.Add("@display_order", SqlDbType.Int).Value = ci.display_order;
                        cmd.Parameters.Add("@charge_id", SqlDbType.BigInt).Value = ci.charge_id;
                        cmd.Parameters.Add("@narrative_line", SqlDbType.Int).Value = ci.narrative_line;
                        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ci.ID;
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "0";
                        cmd.Parameters.Add("@insert_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@narrative", SqlDbType.NVarChar).Value = ci.narrative;
                        cmd.ExecuteNonQuery();
                    }

                    //cmd.CommandText = CommisionInvoiceSQL.CountCommissionInvoiceTempProforma();
                    //cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                    //cmd.Parameters.Clear();
                    //cmd.Parameters.Add("@company", SqlDbType.NVarChar).Value = ci.company.Trim();
                    //cmd.Parameters.Add("@vessel_name", SqlDbType.NVarChar).Value = ci.vessel_name.Trim();
                    //cmd.Parameters.Add("@voyage_no", SqlDbType.NVarChar).Value = ci.voyage_no.Trim();
                    //cmd.Parameters.Add("@invoice_date", SqlDbType.DateTime).Value = ci.invoice_date;
                    //cmd.Parameters.Add("@invoice_amount", SqlDbType.Decimal).Value = ci.invoice_amount;
                    //cmd.Parameters.Add("@charge_type", SqlDbType.NVarChar).Value = ci.charge_type.Trim();

                    //int found = Convert.ToInt16(cmd.ExecuteScalar());
                    //if (found == 0)
                    //{
                    //    //cmd.Parameters.Add("@paid", SqlDbType.NVarChar).Value = ci.paid;
                    //    //cmd.Parameters.Add("@paid_date", SqlDbType.NVarChar).Value = ci.paid_date;
                    //    //cmd.Parameters.Add("@charge_addr_comm", SqlDbType.NVarChar).Value = ci.charge_addr_comm;
                    //    //cmd.Parameters.Add("@charge_collect_comm", SqlDbType.NVarChar).Value = ci.charge_collect_comm;
                    //    //cmd.Parameters.Add("@charge_non_collect_comm", SqlDbType.NVarChar).Value = ci.charge_non_collect_comm;
                    //    //cmd.Parameters.Add("@voyage_type", SqlDbType.NVarChar).Value = ci.voyage_type;
                    //    cmd.Parameters.Add("@invoice_number", SqlDbType.NVarChar).Value = ci.invoice_number.Trim();
                    //    cmd.Parameters.Add("@invoice_type", SqlDbType.NVarChar).Value = ci.invoice_type.Trim();
                    //    cmd.Parameters.Add("@vessel_code", SqlDbType.NVarChar).Value = ci.vessel_code.Trim();
                    //    cmd.Parameters.Add("@profit_centre", SqlDbType.NVarChar).Value = ci.profit_centre.Trim();
                    //    cmd.Parameters.Add("@charge_description", SqlDbType.NVarChar).Value = ci.charge_description.Trim();
                    //    cmd.Parameters.Add("@invoice_currency", SqlDbType.NVarChar).Value = ci.invoice_currency.Trim();
                    //    cmd.Parameters.Add("@invoice_due_date", SqlDbType.DateTime).Value = ci.invoice_due_date;
                    //    cmd.Parameters.Add("@raised_to_final_by", SqlDbType.NVarChar).Value = ci.raised_to_final_by.Trim();
                    //    cmd.Parameters.Add("@charge_amount", SqlDbType.Decimal).Value = ci.charge_amount;
                    //    //cmd.Parameters.Add("@paid", SqlDbType.Int).Value = ci.paid;
                    //    //cmd.Parameters.Add("@paid_date", SqlDbType.DateTime).Value = new DateTime(ci.paid_date.Year, ci.paid_date.Month, ci.paid_date.Day);
                    //    cmd.Parameters.Add("@charge_addr_comm", SqlDbType.Decimal).Value = ci.charge_addr_comm;
                    //    cmd.Parameters.Add("@charge_collect_comm", SqlDbType.Decimal).Value = ci.charge_collect_comm;
                    //    cmd.Parameters.Add("@charge_non_collect_comm", SqlDbType.Decimal).Value = ci.charge_non_collect_comm;
                    //    cmd.Parameters.Add("@voyage_type", SqlDbType.NVarChar).Value = ci.voyage_type;
                    //    cmd.Parameters.Add("@collect_comm", SqlDbType.Decimal).Value = ci.collect_comm;
                    //    cmd.Parameters.Add("@collect_comm2", SqlDbType.Decimal).Value = ci.collect_comm2;
                    //    cmd.Parameters.Add("@collect_comm3", SqlDbType.Decimal).Value = ci.collect_comm3;
                    //    cmd.Parameters.Add("@collect_comm4", SqlDbType.Decimal).Value = ci.collect_comm4;

                    //    cmd.Parameters.Add("@paid", SqlDbType.Int).Value = ci.paid;
                    //    cmd.Parameters.Add("@display_order", SqlDbType.Int).Value = ci.display_order;
                    //    cmd.Parameters.Add("@charge_id", SqlDbType.BigInt).Value = ci.charge_id;
                    //    cmd.Parameters.Add("@narrative_line", SqlDbType.Int).Value = ci.narrative_line;
                    //    cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ci.ID;

                    //    cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "0";
                    //    cmd.Parameters.Add("@insert_date", SqlDbType.DateTime).Value = DateTime.Now;
                    //    cmd.CommandText = CommisionInvoiceSQL.InsertCommissionInvoiceTemp();
                    //    cmd.ExecuteNonQuery();
                    //}
                    //updating display order
                    //else
                    //{
                    //    cmd.CommandText = CommisionInvoiceSQL.CommissionInvoiceTemp();
                    //    ci.commission_invoice_id = Convert.ToInt32(cmd.ExecuteScalar());
                    //    cmd.Parameters.Clear();
                    //    cmd.Parameters.Add("@display_order", SqlDbType.Int).Value = ci.display_order;
                    //    cmd.Parameters.Add("@charge_id", SqlDbType.BigInt).Value = ci.charge_id;
                    //    cmd.Parameters.Add("@narrative_line", SqlDbType.Int).Value = ci.narrative_line;
                    //    cmd.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = ci.commission_invoice_id;
                    //    cmd.CommandText = CommisionInvoiceSQL.UpdateCommissionInvoiceTemp();
                    //    cmd.ExecuteNonQuery();
                    //}
                }
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.SoftmarSqlConnection.Close();
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public void ImportDataSoftmarToMiddleLayer(DateTime date, SoftmarType type)
        {
            try
            {
                IList commissionInvoices = new ArrayList();
                m_dataBaseConectivity.SoftmarSqlConnection.Open();
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.SoftmarSqlConnection;
                switch (type)
                {
                    case SoftmarType.SOFTMAR_COMMISSION_INVOICE_TCRELET:
                        cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByTCReletTypeAndInvoiceTypeCommissionByDate();
                        break;
                    case SoftmarType.SOFTMAR_COMMISSION_INVOICE_VOYAGE_CARGO_RELET:
                        cmd.CommandText = CommisionInvoiceSQL.GetCommisionInvoiceByVCReletTypeAndInvoiceTypeCommissionByDate();
                        break;
                    case SoftmarType.SOFTMAR_FREIGHT_HIRE_INVOICE:
                        cmd.CommandText = CommisionInvoiceSQL.GetFreightHireInvoiceByDate();
                        break;
                }
                cmd.Parameters.Add("@invoiceDate", SqlDbType.NVarChar).Value = date.ToString("dd-MM-yyyy");
                cmd.CommandTimeout = 300;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, false));
                }
                rd.Close();

                foreach (CommissionInvoice ci in commissionInvoices)
                {
                    cmd.CommandText = CommisionInvoiceSQL.CountCommissionInvoiceTemp();
                    cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@invoice_type", SqlDbType.NVarChar).Value = ci.invoice_type;
                    cmd.Parameters.Add("@company", SqlDbType.NVarChar).Value = ci.company;
                    cmd.Parameters.Add("@vessel_name", SqlDbType.NVarChar).Value = ci.vessel_name;
                    cmd.Parameters.Add("@vessel_code", SqlDbType.NVarChar).Value = ci.vessel_sid;
                    cmd.Parameters.Add("@voyage_no", SqlDbType.NVarChar).Value = ci.voyage_no;
                    cmd.Parameters.Add("@profit_centre", SqlDbType.NVarChar).Value = ci.profit_centre;
                    cmd.Parameters.Add("@invoice_date", SqlDbType.DateTime).Value = ci.invoice_date;
                    cmd.Parameters.Add("@charge_description", SqlDbType.NVarChar).Value = ci.charge_description;
                    cmd.Parameters.Add("@invoice_number", SqlDbType.NVarChar).Value = ci.invoice_number;
                    cmd.Parameters.Add("@invoice_amount", SqlDbType.Decimal).Value = ci.invoice_amount;
                    cmd.Parameters.Add("@invoice_currency", SqlDbType.NVarChar).Value = ci.invoice_currency;
                    cmd.Parameters.Add("@invoice_due_date", SqlDbType.DateTime).Value = ci.invoice_due_date;
                    cmd.Parameters.Add("@charge_type", SqlDbType.NVarChar).Value = ci.charge_type;
                    cmd.Parameters.Add("@raised_to_final_by", SqlDbType.NVarChar).Value = ci.raised_to_final_by;
                    cmd.Parameters.Add("@charge_amount", SqlDbType.Decimal).Value = ci.charge_amount;
                    int found = Convert.ToInt16(cmd.ExecuteScalar());
                    if (found == 0)
                    {
                        cmd.Parameters.Add("@pickup_flag", SqlDbType.NVarChar).Value = "0";
                        cmd.Parameters.Add("@insert_date", SqlDbType.DateTime).Value = DateTime.Now;
                        cmd.CommandText = CommisionInvoiceSQL.InsertCommissionInvoiceTemp();
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.SoftmarSqlConnection.Close();
                m_dataBaseConectivity.InterfaceSqlConnection.Close();

            }
        }
        public IList GetAllPendingTCReletCommission()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                //cmd.CommandText = CommisionInvoiceSQL.GetAllPendingTCReletCommission();
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingCommissionInvoice();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllPendingProforma()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingProforma();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, ""));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public int GetAllPendingTCReletCommissionCount()
        {
            int commissionInvoices = 0;
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingTCReletCommissionCount();
                commissionInvoices = Convert.ToInt16(cmd.ExecuteScalar());
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllPendingFreightHireCommission()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                //cmd.CommandText = CommisionInvoiceSQL.GetAllPendingFreightHireCommission();
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingFreightHireInvoice();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public int GetAllPendingFreightHireCommissionCount()
        {
            int commissionInvoices = 0;
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingFreightHireCommissionCount();
                commissionInvoices = Convert.ToInt16(cmd.ExecuteScalar());
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllPendingTCReletCommission(string search)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                //cmd.CommandText = CommisionInvoiceSQL.GetAllPendingTCReletCommission(search);
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingCommissionInvoice(search);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllPendingProforma(string search)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingProforma(search);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, ""));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllPendingFreightHireCommission(string search)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                //cmd.CommandText = CommisionInvoiceSQL.GetAllPendingFreightHireCommission(search);
                cmd.CommandText = CommisionInvoiceSQL.GetAllPendingFreightHireInvoice(search);
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProforma()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProforma();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaPending()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaPending();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaPendingLastMOnthPeriod()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime firstDay = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1, 0, 0, 0);
                DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month));
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaCommissionCreditPendingLastMOnthPeriod()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime today = m_lastDateProforma;//DateTime.Today;
                DateTime firstDay = m_executeByDateProforma ? m_fromDateProforma :
                    new DateTime(today.Year, today.Month - 2 <= 0 ? today.Month - 2 + 12 : today.Month - 2, 1, 0, 0, 0);//last three months
                //DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month));
                DateTime LastDay = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year,today.Month), 23, 59, 59);
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaCommissionCreditPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaCommissionCreditPendingLastMOnthPeriod(DateTime firstDay)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month), 23, 59, 59);
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaCommissionCreditPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaChargeDebitPendingLastMOnthPeriod()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime today = m_lastDateProforma;//DateTime.Today;
                DateTime firstDay = m_executeByDateProforma ? m_fromDateProforma :
                    new DateTime(today.Year, today.Month - 2 <= 0 ? today.Month - 2 + 12 : today.Month - 2, 1, 0, 0, 0);//last three months
                //DateTime firstDay = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1, 0, 0, 0);
                //DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month));
                DateTime LastDay = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month), 23, 59, 59);
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaChargeDebitPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaChargeDebitPendingLastMOnthPeriod(DateTime firstDay)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month), 23, 59, 59);
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaChargeDebitPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaChargeCreditPendingLastMOnthPeriod()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime today = m_lastDateProforma;
                DateTime firstDay = m_executeByDateProforma ? m_fromDateProforma :
                    new DateTime(today.Year, today.Month - 2 <= 0 ? today.Month - 2 + 12 : today.Month - 2, 1, 0, 0, 0);//last three months
                //DateTime firstDay = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1, 0, 0, 0);
                //DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month));
                DateTime LastDay = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month), 23, 59, 59);
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaChargeCreditPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaChargeCreditPendingLastMOnthPeriod(DateTime firstDay)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month), 23, 59, 59);
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaChargeCreditPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetAllProformaPendingLastMOnthPeriod(DateTime firstDay)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                DateTime LastDay = new DateTime(firstDay.Year, firstDay.Month, DateTime.DaysInMonth(firstDay.Year, firstDay.Month));
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllProformaPendingDuringLastMonthPeriod();
                //cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = new DateTime(firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Year, firstDay.Subtract(new TimeSpan(1, 0, 0, 0)).Month, 26, 0, 0, 0);
                //cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = new DateTime(firstDay.Year, firstDay.Month, 25, 23, 59, 59);
                cmd.Parameters.Add("@invoice_date_from", SqlDbType.DateTime).Value = firstDay;
                cmd.Parameters.Add("@invoice_date_to", SqlDbType.DateTime).Value = LastDay;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new InvoiceProforma(rd));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public IList GetProformaItem(InvoiceProforma ci)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetProformaByInvoiceDateVoyageNoVesselCompanyAmount();
                cmd.Parameters.Add("@company", SqlDbType.NVarChar).Value = ci.company.Trim();
                cmd.Parameters.Add("@vessel_name", SqlDbType.NVarChar).Value = ci.vessel_name.Trim();
                cmd.Parameters.Add("@voyage_no", SqlDbType.NVarChar).Value = ci.voyage_no.Trim();
                cmd.Parameters.Add("@invoice_date", SqlDbType.DateTime).Value = ci.invoice_date;
                cmd.Parameters.Add("@invoice_amount", SqlDbType.Decimal).Value = ci.invoice_amount;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, true));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public void GetCollectCommission(CommissionInvoice ci)
        {
            try
            {
                m_dataBaseConectivity.SoftmarSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.SoftmarSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetCollectCommission();
                cmd.Parameters.Add("@vmvoyageno", SqlDbType.Int).Value = ci.ID;
                cmd.Parameters.Add("@narrative", SqlDbType.NVarChar).Value = ci.charge_description;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    ci.collect_comm = rd["collect_comm"] is DBNull ? 0 : Convert.ToDecimal(rd["collect_comm"]);
                    ci.collect_comm2 = rd["collect_comm2"] is DBNull ? 0 : Convert.ToDecimal(rd["collect_comm2"]);
                    ci.collect_comm3 = rd["collect_comm3"] is DBNull ? 0 : Convert.ToDecimal(rd["collect_comm3"]);
                    ci.collect_comm4 = rd["collect_comm4"] is DBNull ? 0 : Convert.ToDecimal(rd["collect_comm4"]);
                }
                rd.Close();
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.SoftmarSqlConnection.Close();
            }
        }
        public IList GetAllCommission()
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllCommission();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(rd["invoice_number"].ToString());
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }

        public IList GetCommissionItem(string invoice_number)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetCommissionByInvoiceNumber();
                cmd.Parameters.Add("@invoice_number", SqlDbType.NVarChar).Value = invoice_number;
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    commissionInvoices.Add(new CommissionInvoice(rd, true));
                }
                rd.Close();
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
        public void UpdateNarrative() //09122013 one time only
        {
            int count = 0;
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                m_dataBaseConectivity.InterfaceSqlConnection_b.Open();
                m_dataBaseConectivity.SoftmarSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                cmd.CommandText = CommisionInvoiceSQL.GetAllChargeID();
                SqlDataReader rd = cmd.ExecuteReader();

                while (rd.Read())
                {
                    count++;
                    int commission_invoice_id = rd["commission_invoice_id"] is DBNull ? 0 : Convert.ToInt32(rd["commission_invoice_id"]);
                    long charge_id = rd["charge_id"] is DBNull ? 0 : Convert.ToInt64(rd["charge_id"]);

                    SqlCommand cmd_b = new SqlCommand();
                    cmd_b.Connection = m_dataBaseConectivity.SoftmarSqlConnection;
                    cmd_b.CommandText = CommisionInvoiceSQL.GetNarrationByChargeID();
                    cmd_b.Parameters.Add("@chargeid", SqlDbType.BigInt).Value = charge_id;
                    object obj = cmd_b.ExecuteScalar();
                    if (obj != null)
                    {
                        string narrative = obj.ToString();
                        cmd_b.Connection = m_dataBaseConectivity.InterfaceSqlConnection_b;
                        cmd_b.CommandText = CommisionInvoiceSQL.UpdateNarrative();
                        cmd_b.Parameters.Add("@commission_invoice_id", SqlDbType.Int).Value = commission_invoice_id;
                        cmd_b.Parameters.Add("@narrative", SqlDbType.VarChar).Value = narrative;
                        cmd_b.ExecuteNonQuery();
                    }
                }
                rd.Close();
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.SoftmarSqlConnection.Close();
                m_dataBaseConectivity.InterfaceSqlConnection_b.Close();
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }

        public IList GetInterfacedTransaction(string invoice, string type)
        {
            IList commissionInvoices = new ArrayList();
            try
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = m_dataBaseConectivity.InterfaceSqlConnection;
                if (type.Trim() == "SC")
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetCommissionHistoryByInvoiceNumberSC(invoice, type);
                    SqlDataReader rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        commissionInvoices.Add(new InterfacedBatch(rd));
                    }
                    rd.Close();
                    cmd.CommandText = CommisionInvoiceSQL.GetCommissionHistoryByInvoiceNumber(invoice, type);
                    rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        commissionInvoices.Add(new InterfacedBatch(rd));
                    }
                    rd.Close();
                }
                else
                {
                    cmd.CommandText = CommisionInvoiceSQL.GetCommissionHistoryByInvoiceNumber(invoice, type);
                    SqlDataReader rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {
                        commissionInvoices.Add(new InterfacedBatch(rd));
                    }
                    rd.Close();
                }
                
                return commissionInvoices;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                m_dataBaseConectivity.InterfaceSqlConnection.Close();
            }
        }
    }
}
